Scoping issue with import

Steve Holden steve at holdenweb.com
Tue Mar 1 05:18:38 EST 2005


James Stroud wrote:
> Say I have a module, we'll call it "my_imported_mod". It contains a function 
> in it that calls another function, "myfun". The "myfun" function is in the 
> module "my_main_mod", that imports "my_imported_mod".
> 
> The code of "my_main_mod" might look like this:
> ==============
> from my_imported_mod import *
> 
> def myfun():
>   print "stuff"
> ==============
> 
> the code of "my_imported_mod" might look like this:
> ==============
> def somefun():
>   myfun()
> ==============
> 
> When trying to execute the function somefun(), I get a
> NameError: global name 'myfun' is not defined
> 
> How to rectify this with minimal code change? How to let imported modules know 
> about the namespace they are getting imported into? I do not want to 
> restructure my code right now.
> 
> Thanks in advance for help.
> 
> James

You have had some good advice about avoiding circular imports.

I just wanted you to consider the coupling of your module. If the called 
function is calling a function inside the module that's calling it, this 
is often a clue that the inner function should be passed as a parameter 
to the first one.

Let me know if this isn't comprehensible and I'll give you an example, 
but to show this being done inside a single module I present the code below:

  >>> def caller(f, arg):
  ...   return f(arg)
  ...
  >>> def call(summat):
  ...   print summat * 3
  ...
  >>> caller(call, 21)
  63
  >>> caller(call, "string")
  stringstringstring

This also demonstrates quite nicely how Python doesn't choose to 
discriminate between integers and strings at compile time, applying the 
correct definition of multiplication when the operation actually has to 
be performed.

Some people hate this, most people who read comp.lang.python regularly 
will be quite happy to explain why it's a Good Thing (tm).

regards
  Steve



More information about the Python-list mailing list