Maintainability (was Re: Stackless & String-processing)
Tim Peters
tim_one at email.msn.com
Mon Jul 26 00:58:28 EDT 1999
[Fred L. Drake, "import whatever as something_else"]
> ...
> As I said, I haven't noticed this come up for a while, so maybe I'm
> the only one, but I think this would encourage clarity and
> "localizing" the names of imported modules (adding a leading _ so when
> others "import *" from our modules their namespace isn't polluted too
> much).
New keywords are dead in the water, so maybe you'll find the attached
useful. Make it fancier, e.g. _my_import(globals(),
something_else="whatever") if you like. A version of this used to do that,
but with the functional interface it was too confusing for me.
go-ahead-import-my-day-ly y'rs - tim
def _pvt_import(globs, modname, *items):
"""globs, modname, *items -> import into globs with leading "_".
If *items is empty, set globs["_" + modname] to module modname.
If *items is not empty, import each item similarly but don't
import the module into globs.
Leave names that already begin with an underscore as-is.
# import math as _math
>>> _pvt_import(globals(), "math")
>>> round(_math.pi, 0)
3.0
# import math.sin as _sin and math.floor as _floor
>>> _pvt_import(globals(), "math", "sin", "floor")
>>> _floor(3.14)
3.0
"""
mod = __import__(modname, globals())
if items:
for name in items:
xname = name
if xname[0] != "_":
xname = "_" + xname
globs[xname] = getattr(mod, name)
else:
xname = modname
if xname[0] != "_":
xname = "_" + xname
globs[xname] = mod
More information about the Python-list
mailing list