aphex
aphex

Reputation: 3412

NameError: global name is not defined

I know there are a bunch of similar questions, but they didn't help me to understand my problem. Also I have 3 modules:

First one is model:

from datetime import datetime
from elixir import *
from run_test import create_db
from sqlalchemy.schema import UniqueConstraint
class ValueTest(Test): 
    value = Field(Integer)
    def __init__(self, name, value):
        '''
        Constructor
        '''
        self.name = name;
        self.value = value

If I run the test method from the second module named run_test, there aren't any problems

from model import *
def main():
    test();
def test():
    test = ValueTest("test",2)
if __name__ == "__main__":
    main()

But when I try something like that, I get the the well known error NameError: global name 'ValueTest' is not defined

import run_test
def main():
    run_test.test()
if __name__ == '__main__':
    main()

Upvotes: 2

Views: 7055

Answers (2)

cdhowie
cdhowie

Reputation: 169328

When you import a module, you don't import the names it has imported; you only import the names it defines itself. You still need to do from model import ValueTest in the last script.

If from foo import * imported every name that foo imported into its own scope, a single import something might also import every symbol in os or sys for example. It would be a nightmare.


Actually, this is not true. The symbols imported from the module are only those defined by the __all__ list set in that module. (If not present, all symbols not starting with _ are indeed imported.)

Thanks Ethan for the correction.

Upvotes: 6

Ethan Furman
Ethan Furman

Reputation: 69240

The problem is you have circular imports happening. run_test is importing model, which in turn is importing run_test. Strange things happen when circular imports are used. If you can, put the common functions (create_db, in your example) into another module, then model can import it from there and not from run_test.

Upvotes: -1

Related Questions