from-import on non-module objects?
tim.one at home.com
Sun Feb 4 05:31:38 EST 2001
> Have there been thoughts on having from-import used on non-module
> objects in order to introduce attributes from a given object into the
> current scope?
> Unless I misunderstood the explanation, I believe this exact thing
> is one of the features being included in Python 2.1.
The description of this change is the NEWS file for 2.1a1 and 2.1a2 was
incomplete; it will be clearer in the next release.
Short course: in
from M import x
M no longer needs to be a true module object (which earlier NEWS said), but
the name "M" *must* be a key in sys.modules (which info was missing). So
this isn't a hack aimed at letting people do bizarre things with
from-import, it's a hack aimed at letting people use "module-like objects".
Python has a long tradition of loosening type restrictions over time, and
this was a natural part of that tradition: if an object supports getattr,
it supports the only thing the "import" part of from-import really needs.
The "from" part still needs "a module name", though, but the operational
definition of "a module name" is "a name that appears as a key in
sys.modules". So meet those two requirements, and Python couldn't care less
whether it's "a real module" anymore.
Really bad idea (running under 2.1a2):
>>> somelist = [1, 2, 3, 2, 1]
>>> from somelist import count # blows up
Traceback (most recent call last):
File "<pyshell#2>", line 1, in ?
from somelist import count # blows up
ImportError: No module named somelist
>>> import sys
>>> sys.modules["somelist"] = somelist
>>> from somelist import count # works, for some meaning of "works"
>>> count(1), count(2), count(3), count(4)
(2, 2, 1, 0)
Don't try that at home; you'll be shot if you do <0.9 bang>.
useful-examples-left-to-your-fertile-imaginations-ly y'rs - tim
More information about the Python-list