[Tutor] seeking design pattern

Cameron Simpson cs at cskk.id.au
Sat Aug 24 21:47:08 EDT 2019


On 24Aug2019 20:39, bob gailer <bgailer at gmail.com> wrote:
>I desire to import some functions form a module and give them access 
>to names in the main module namespace. Example:
>
>m.py ---------------
>
>def a():
>    print(s)
>
>interactive interpreter ---------------
>>>> s = 3
>>>> from m import a
>>>> a()
>Traceback (most recent call last):
>  File "<input>", line 1, in <module>
>  File "N:\m.py", line 2, in a
>    print(s)
>NameError: name 's' is not defined
>
>My expectation was that the function, having been imported into the 
>main module, would access variables in the main module, but alas, not 
>the case.

No, that would be a disaster.

>Is there a workaround? ( easy, "clean", pythonic)

m.py
  def a(s):
    print(s)

s = 3
from m import a
a(s)

The interpret name "s" is distinct from the function parameter name "s".  
By passing a(s), the object referenced by the name "s" in the 
interactive scope is presented (coindidentally) as the name "s" in the 
function "a".

Can you describe why you would want the original behaviour you describe?

Bear in mind that most Python names can be rebound. So you can rebind 
"print" to a function of your own choosing. Should a() also honour that?

Try to provide something you want to do in the real world which would 
benefit from this name behaviour.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list