Short answer: No, it's impossible, and you'll have to use a prefix.
It's important to understand that from foo import x, y
is copying x
to your namespace. It's equivallent to:
import foo
# COPY TO YOUR NAMESPACE
x = foo.x
y = foo.y
# `from foo import` does NOT leave `foo` in your namespace
def foo
This way, each module will get a local copy of x
and y
. Changing x
won't be seen in other modules, and you won't see changes other modules do :-(
To change the central copy of a variable you must import the module itself: import foo
and change foo.x
. This way only one copy exists and everybody is accessing it :-)
[The linked questions also mention the possibility to put the shared variable in the module builtin. DON'T! This would eliminate the prefix for reading it, but not for writing, and is extremely bad style.]
A note in defense of Python
If you resent the need to use a foo.
prefix here, you'll probably also resent the need for the self.
prefix to access object variables. The bottom line is that's how Python works - since you don't declare variables, there is no choice but to use prefixes.
But there is also an upside: when reading Python code, you easily see where each variable lives. IMHO that's very good.
Supporting evidence: in other languages like C++/Java, many people observe conventions like an m_
prefix on all object variable names to achieve a similar effect...
Style remarks
You don't need import foo as bar
, just use import foo
.
The as
form doesn't do anything new, it just renames it, which is just confusing.
It's only useful if "foo" is a very long name; a particularly accepted case is when "foo" lives deep in some package, so you can do import long.package.foo as foo
.
The from foo import *
is considered very bad style in programs because:
The person reading your code won't know where names came from.
It pollutes your namespace, which can lead to subtle bugs when names from
different modules clash.
The explicit form from foo import x, y
is OK, but starts suffering from the same problems if you use many names from the module.
In such cases, it's best to import foo
and explicitly write foo.x
, foo.y
.
Bottom line: when in doubt, a simple import foo
is best.
Exception: It is very handy to use import *
when experimenting at the interactive interpreter. Note however that it doesn't play well with reload()
, so don't use it when debugging changing code. (To debug a module you are writing, it's best to launch a fresh interpreter inside the module's namespace - python -i mymodule.py
/ F5 in IDLE.)