I came across a strange situation while writing two separate functions in same ".py" file. I am using python 2.7.12. Here is my code:
def do_the_job(n, list):
for i in range(2, n):
a = list[i - 1]
b = list[i - 2]
ap_me = list[i- a] + list[i - b]
list.append(ap_me)
return list
def func_two(n, k):
counter = 0
list = [1, 1]
do_the_job(n,list)
for i in range(n):
if list[i] >= k:
counter += 1
return counter
Then for import, I write from my_py import func_two to console. When I write func_two(10,3) it imports do_the_job function too and runs successfully. However, here comes the reason of the post, when I write do_the_job(7,[1,1]) to console, it errors as NameError: name 'do_the_job' is not defined.
How come I can use do_the_job function as a part of func_two function with importing func_two, but cannot use it on its own with same import status?
Functions are given a reference to a global namespace. That namespace is the module they are defined in.
Because both func_two and do_the_job are defined in the same module, they both 'live' in that namespace. Using the name do_the_job in the body of func_two will be resolved by looking at the globals for func_two and that'll find the other function.
When you import a module, the whole module is always loaded; you can find it in the sys.modules mapping. Once loaded (which only needs to be done once), the importing namespace is updated to add the names you imported; these are just references to objects in the imported module namespace.
So the from my_py import func_two import ensures the my_py module is loaded (stored in sys.modules['my_py']) and then the name func_two is added to your current namespace to reference sys.modules['my_py'].func_two.
You did not, however, import do_the_job into your current namespace, so you can't use that name. It is not part of your global namespace. Either import it explicitly, or reference it via sys.modules['my_py'].do_the_job.
You may want to read up on how Python names work, I can heartily recommend you read Ned Batchelder's Facts and myths about Python names and values. It doesn't directly cover importing, but it does offer vital insights that'll help you understand this specific situation better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With