I propose this as something that is entirely complimentary to importing, not in conflict with it. If you understand what std means, then it's also just as explicit as importing. It's really just another import mechanism which is more convenient in certain (fairly common) circumstances. One could argue (as the paragraph on py.std does) that this is actually more explicit because it never allows module-relative imports. I think it's only really useful if it is idiomatic, or even better built in (without hacking __builtins__), but it's a very simple idiom. The implementation in the py lib is actually just this:
import sys class Std(object): def __init__(self): self.__dict__ = sys.modules def __getattr__(self, name): try: m = __import__(name) except ImportError: raise AttributeError("py.std: could not import %s" % name) return m std = Std()
- Aside: one of the things I hate most (there aren't many) coming to Python from Java is the ability to import a package and then be able to navigate to any subpackage using dot notation. Example:
- >>> import PythonCard >>> PythonCard.components.button Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'module' object has no attribute 'components'
- I have a dream of being able to do this (does anyone else hate the from keyword?):
- >>> import my.deeply.nested.package.function as func # results in error
- Which usually starts out as:
- >>> import my.deeply.nested.package as package >>> package.function(...)
- And then mutates to this when we realize we're only using a single function in that package:
- >>> from my.deeply.nested.package import function as func
And that requires me to rearrange the entire line, which is annoying. And as if that weren't enough trouble with Python's import mechanism, why in the heck couldn't they make the __import__ function "just work" like it's supposed to (i.e. col = __import__("sqlobject.col") should have the same effect as import sqlobject.col as col)?
Maybe the "std" object could be enhanced to fix that problem too. The only downside I can see here might be performance (try exploring std in Pyshell--it's a bit slow on my PIII 733 (then again, Eclipse is nearly useless on this machine)). On the positive side, it's much easier to explore the standard library this way, which is another thing I miss from Java. Eclipse allowed me to explore Java api's through the auto-complete feature, providing JavaDoc tooltips when available--very productive. But now I'm asking for a good IDE which is an entirely different subject. I guess I should check out PyDev again sometime.
Wow, I think you hit a sore spot there.