4

I have two python modules:

//// funcs.py

from classes import *

def func():
    d = D()
    print "func"

if __name__ == "__main__":
    c = C()

//// classes.py

from funcs import *

class C:
    def __init__(self):
        print "C class"
        func()

class D:
    def __init__(self):
        print "D class"

Running funcs.py yields a NameError saying that "global name 'D' is not defined". However if I comment out the creation of the D() instance, everything works fine.

Why does this happen?

Thanks

0

2 Answers 2

5

This one works fine without complicating your code:

///funcs.py

import classes

def func():
    d = classes.D()
    print "func"

if __name__ == "__main__":
    c = classes.C()

///classes.py

import funcs

class C:
    def __init__(self):
        print "C class"
        funcs.func()

class D:
    def __init__(self):
        print "D class"

Sometimes it's much better to use simple import, than from ... import .... There is quite good article on that: http://effbot.org/zone/import-confusion.htm

Sign up to request clarification or add additional context in comments.

Comments

2

The problem occurs due to the attempt to use a cyclically imported module during module initialization. To clarify, using the "from module use *" requires that a module be compiled. Instead if you switch to using "import module" in both cases, it should work fine.

1 Comment

"requires that a module be compiled" is misleading at best. The module code is loaded, compiled and run either way. But from m import * copies everything that's in the module at that point in time while import m gives a reference to the module object - and hence makes later modifications visible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.