Hello:

Please help me to solve this:

>>> def printA():
... try: print a
... except NameError: print 'variable undefined'
...
>>> printA()
variable undefined
>>> a = "foo"
>>> printA()
foo
>>>

I tried to do the same think by importing a file "test.py" which has the function 'printA()'

Content of the file 'test.py'
=================
def printA():
try: print a
except NameError: print 'variable undefined'

>>> from test import *
>>> printA()
variable undefined
>>> a = "foo"
printA()
variable undefined
>>>

Any idea why the variable 'a' is still undefined in this case?

I would recomment to always use the namespace of a module. It makes your code much easier to understand.

Here is the module ...

# a simple module save as test.py

def printA():
    try:
        print a
    except NameError:
        print 'variable undefined'

# test the module as such
if __name__ == '__main__':
    printA()
    print '-'*20
    a = 'hello'
    printA()

Now you can use the module ...

# use the module test.py

import test  # establish the namespace test

test.printA()
print '-'*20
test.a = 'hello'
test.printA()

Now it will work correctly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.