[Tutor] seeking design pattern

Alan Gauld alan.gauld at btinternet.com
Sun Aug 25 03:48:10 EDT 2019


On 25/08/2019 01:39, bob gailer wrote:
>  >>> s = 3

This defines a name s in the current namespace


>  >>> from m import a

This imports the *name* a from the module m.


a refers to a function object in the module m.

The function object remains in the module namespace,
it cannot be imported. import only makes the name visible.

Understanding the difference between names and
values is absolutely critical in Python.


>  >>> 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

This calls the function in module m. And the function
tries to find a name called s but cannot for there is
no s defined in m.


> My expectation was that the function, having been imported into the main

You do not import the function, you import the name. The name is still
a reference to the function inside the module.


This is why relying on global variables is nearly always a bad idea.
Instead pass the value as an argument to the function (which must
of course be defined to have a parameter):


def a(s) print(s)

a(s)



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

There is a workaround for situations where you are not in
control of the module code.

You could create your own s inside m:


import m

m.s = 3

m.a()


Now a() can see an s inside m.


But that is horrible and the wrong thing to do unless you really have to.

And you need to remember to change m.s everytime you change s if
you want to call a() in the future. Please avoid that if you possibly can.

The parameter/argument mechanism is there for a reason, use it.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list