[Python-ideas] Implicit submodule imports

Thomas Gläßle t_glaessle at gmx.de
Wed Sep 24 19:57:36 CEST 2014


Hey folks,

What do you think about making it easier to use packages by
automatically importing submodules on attribute access.

Consider this example:

    >>> import matplotlib
    >>> figure = matplotlib.figure.Figure()
    AttributeError: 'module' object has no attribute 'figure'

For the newcomer (like me some months ago) it's not obvious that the
solution is to import matplotlib.figure.

Worse even: it may sometimes/later on work, if the submodule has been
imported from another place.

How, I'd like it to behave instead (in pseudo code, since `package` is
not a python class right now):

    class package:

        def __getattr__(self, name):
            try:
                return self.__dict__[name]
            except KeyError:
                # either try to import `name` or raise a nicer error message

The automatic import feature could also play nicely when porting a
package with submodules to or from a simple module with namespaces (as
suggested in [1]), making this transition seemless to any user.

I'm not sure about potential problems from auto-importing. I currently
see the following issues:

- harmless looking attribute access can lead to significant code
execution including side effects. On the other hand, that could always
be the case.

- you can't use attribute access anymore to test whether a submodule is
imported (must use sys.modules instead, I guess)


In principle one can already make this feature happen today, by
replacing the object in sys.modules - which is kind of ugly and has
probably more flaws. This would also be made easier if there were a
module.__getattr__ ([2]) or "metaclass" like feature for modules (which
would be just a class then, I guess).

Sorry, if this has come up before and I missed it. Anyhow, just
interested if anyone else considers this a nice feature.

Best regards,
Thomas



[1]
https://mail.python.org/pipermail/python-ideas/2014-September/029341.html
[2] https://mail.python.org/pipermail/python-ideas/2012-April/014957.html


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 949 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140924/474838f2/attachment.sig>


More information about the Python-ideas mailing list