Python Forum

Full Version: global namespace of an imported function (2 Qs)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
the global namespace of an imported function seems to be separate/distinct from the global namespace of the caller. so when is the function's global namespace created? when it is imported or when the function is first called? is there a way for imported code to access variables from the global namespace of what is importing it at import time?
The namespace is created when it is imported, and I believe only when it is first imported. Any top-level code in the module is executed at that time, and can access anything defined above it in that namespace.
(Oct-08-2018, 02:07 AM)ichabod801 Wrote: [ -> ]The namespace is created when it is imported, and I believe only when it is first imported. Any top-level code in the module is executed at that time, and can access anything defined above it in that namespace.
and what all does that include?

i would like to set a variable of a specific name followed by importing a module. i want have that module access that variable (it would know the name) and use that value to do different things like defining different functions.
Why would you want to do all that? Why not just pass the variable to a function in the module?
in the one case i have first, i want the variable to help the module decide which code to define the function with. the is not the actual code, just a fun example.
if yesdoit:
    def doit():
        print('yes')
        return 'yes'
else:
    def what():
        return
the code above is the typical uselessness you might see in school classes. it's just to show the concept's codability.

i think i have found a solution: set an environment variable.

i have done this definition of a function under conditional logic before to define functions differently based which version of python is running. this allowed me to work with the unicode type in python2 and the bytes type in python3. i call this split definition.
if str == bytes:
    def prthing(x):
        if isinstance(x,(str,unicode)):
            print x
            return
        elif isinstance(x,bytearray):
            print str(x)
            return
        else:
            print repr(x)
            return
else:
    def prthing(x):
        if isinstance(x,str):
            return print(x)
        elif isinstance(x,(bytes,bytearray)):
            return print(''.join([chr(c) for c in x]))
        else:
            return print(repr(x))
but i do have different kinds of needs for split definitions. now i have come to where it is a setting by the code doing the importing.