tafi
tafi

Reputation: 227

Python scope / namespace issue

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

Upvotes: 4

Views: 542

Answers (2)

Gandi
Gandi

Reputation: 3652

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

Upvotes: 5

Vijay Varadan
Vijay Varadan

Reputation: 628

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.

Upvotes: 2

Related Questions