classification
Title: strange import visibility
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: geryon, r.david.murray
Priority: normal Keywords:

Created on 2013-01-25 12:57 by geryon, last changed 2013-01-25 13:54 by geryon. This issue is now closed.

Messages (3)
msg180574 - (view) Author: Stephan (geryon) Date: 2013-01-25 12:57
$ cat a.py
import dbus
import b
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
print "Hello, World."
$ cat b.py
import dbus.mainloop.glib
$ python a.py
Hello, World.
$

If I remove the “import b” line, the output is:

$ python a.py
Traceback (most recent call last):
  File "a.py", line 3, in <module>
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
AttributeError: 'module' object has no attribute 'mainloop'
$

In my opinion this is inconsistent. Either both versions should fail with that error, because “dbus.mainloop.glib” is imported in “b”, not “a”; or both should succeed, because “a” imports dbus.

This is Python 2.7.3 and python-dbus 1.0.0 on Ubuntu 12.4.2
msg180576 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2013-01-25 13:21
I agree that this is not immediately intuitive.

What you need to know is that modules are part of the global state.  When b imports dbus.mainloop.glib, it affects the global state of the module dbus, causing mainloop.glib to be defined when 'a' references it.

The fact that modules are global state is inherent in Python's design, and is the reason that "monkey patching" works.
msg180582 - (view) Author: Stephan (geryon) Date: 2013-01-25 13:54
Thanks! I was not aware of this yet.
History
Date User Action Args
2013-01-25 13:54:59geryonsetmessages: + msg180582
2013-01-25 13:21:57r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg180576

resolution: not a bug
stage: resolved
2013-01-25 12:57:46geryoncreate