On Sep 24, 2014, at 10:57, Thomas Gläßle <t_glaessle@gmx.de> wrote:
Hey folks,
What do you think about making it easier to use packages by automatically importing submodules on attribute access.
Doesn't IPython already have this feature as an option? I know that not everyone who uses scipy and matplotlib uses IPython, and they aren't the only two packages used by novices that have sub modules they don't automatically import for you, but... I'm guessing the percentages are high. Of course this support could also be added to scipy and matplotlib itself. And maybe importlib could have a function that makes automatic lazy loading of submodules on demand a one-liner for packages that want to support it.
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
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/