Scope of "library" methods
Posted
by JS
on Stack Overflow
See other posts from Stack Overflow
or by JS
Published on 2010-04-07T23:33:39Z
Indexed on
2010/04/07
23:43 UTC
Read the original article
Hit count: 271
Hello,
I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.
Background:
I'm using the
'if name in "main"'
construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the modules.
To keep things "purdy" and manageable, I've created a small method to simplify the testing of method calls:
def pprint_vars(var_in):
print("%s = '%s'" % (var_in, eval(var_in)))
Calling pprint_vars with:
pprint_vars('some_variable_name')
prints:
some_variable_name = 'foo'
All fine and good.
Problem statement:
Not happy to just KISS, I had the brain-drizzle to move my handy-dandy 'pprint_vars' method into a separate file named 'debug_tools.py' and simply import 'debug_tools' whenever I wanted access to 'pprint_vars'.
Here's where things fall apart. I would expect
import debug_tools
foo = bar
debug_tools.pprint_vars('foo')
to continue working its magic and print:
foo = 'bar'
Instead, it greets me with:
NameError: name 'some_var' is not defined
Irrational belief:
I believed (apparently mistakenly) that import puts imported methods (more or less) "inline" with the code, and thus the variable scoping rules would remain similar to if the method were defined inline.
Plea for help:
Can someone please correct my (mis)understanding of scoping regards imports?
Thanks, JS
© Stack Overflow or respective owner