Does python have something like C++'s using keyword?
-
23-08-2019 - |
Question
In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example:
void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
becomes
void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
Does something similar exist for python, or do I have to fully qualify everything?
I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope.
Solution
As Bill said, Python does have the construction
from X import *
but you can also explicitly specify which names you want imported from the module (namespace):
from X import foo, bar, blah
This tends to make the code even more readable/easier to understand, since someone seeing an identifier in the source doesn't need to hunt through all imported modules to see where it comes from. Here's a related question: Namespace Specification In Absence of Ambuguity
EDIT: in response to Pax's comment, I'll mention that you can also write things like
import X.foo
but then you'll need to write
X.foo.moo()
instead of just
foo.moo()
This is not necessarily a bad thing, of course. I usually use a mixture of the from X import y
and import X.y
forms, whatever I feel makes my code clearest. It's certainly a subjective thing to some extent.
OTHER TIPS
import X
or
from X import *
or
from X import a, b, c
Where X is the Python module you want to use.
It would be helpful for you to give us a Python code sample that you think needs cleaned up.
Sure, python's dynamism makes this trivial. If you had a class buried deep in a namespace: foo.bar.baz.blah, you can do:
def foo:
f = foo.bar.baz.blah
f1 = f()
In addition to David's answer:
- One should use round brackets in
from X import (foo, bar, blah)
for a sake of PEP8. - Full syntax allows renaming (rebinding) package names to their new identifiers within the scope of the current module as in
from foo import bar as baz
.
I recommend to look up the manual for the import keyword, the __import__
built-in and explanation for sys.modules as further reading.
Another option in Python is the construct "as" when importing. For example:
from foo import bar as baz
This will bring foo.bar
in as baz
in the current module which allows the entity to get a different name in the current module, possibly to avoid hiding an existing entity in the current module with the same name.
Note that
from foo import bar
works even if bar
is a module in the foo
package. This lets you limit your namespace pollution without having to name each function/class in foo.bar
that you might care to use. It also aids readers of your code, because they'll see a call to bar.baz()
and have a better idea where baz
came from.