[Tutor] seeking design pattern

Richard Damon Richard at Damon-Family.org
Sat Aug 24 21:47:02 EDT 2019


On 8/24/19 5:39 PM, bob gailer 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.
>
> Is there a workaround? ( easy, "clean", pythonic)
>
>
In python, importing a module doesn't merge the namespaces, but brings
in copies of the definitions so they can be accessed without explicit
mentioning scopes.

One key thing to think about, several modules might have imported a
given module, so having that import change where things that are
accessed in that module get found would be complicated.


One way to do something like what you are asking would be in the calling
module, after the import of m, to write into that modules namespace with
something like


m.s = 3

I think that would then let things in m see the new value of s in their
scope.

-- 
Richard Damon



More information about the Tutor mailing list