How to make a variable's late binding crosses the module boundary?

dn PythonList at DancesWithMice.info
Tue Aug 30 00:05:43 EDT 2022


On 30/08/2022 06.45, Peter J. Holzer wrote:

> The module is imported but it isn't bound to any name in the current
> (global) namespace (obviously there must be some variable bound to it, but
> that's probably a local variable in the importer and it isn't called
> `x`). Then the object bound to the name `y` in the loaed module is bound
> to the name `y` in the current namespace.


Correct!

Build module.py as:
***
CONSTANT = 1

def func():
    pass
***

then in the terminal:
***
Python 3.9.13 (main, May 18 2022, 00:00:00)
[GCC 11.3.1 20220421 (Red Hat 11.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from module import func as f
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>, 'f': <function func at 0x7f6faa8269d0>}
>>> f
<function func at 0x7f6faa8269d0>
>>> f.CONSTANT
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'CONSTANT'
>>> module.CONSTANT
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'module' is not defined

# no mention of module and no access to CONSTANT

>>> import module as m
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>, 'f': <function func at 0x7f6faa8269d0>, 'm': <module
'module' from '/home/dn/Projects/ListQuestions/module.py'>}
>>> m
<module 'module' from '/home/dn/Projects/ListQuestions/module.py'>
>>> m.func
<function func at 0x7f6faa8269d0>
>>> m.CONSTANT
1
>>> module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'module' is not defined

# name module is bound as m, and not available as module

>>> import module
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>, 'f': <function func at 0x7f6faa8269d0>, 'm': <module
'module' from '/home/dn/Projects/ListQuestions/module.py'>, 'module':
<module 'module' from '/home/dn/Projects/ListQuestions/module.py'>}
>>> module.func
<function func at 0x7f6faa8269d0>
>>> module.CONSTANT
1
>>> module
<module 'module' from '/home/dn/Projects/ListQuestions/module.py'>

# now it is available
# also notice how the function (func) now has three
'names'/access-methods but all lead to the same location
***

-- 
Regards,
=dn


More information about the Python-list mailing list