Importing a module with dashes.
Steven D. Majewski
sdm7g at virginia.edu
Thu Oct 26 16:20:56 EDT 2000
On 26 Oct 2000, Igor V. Rafienko wrote:
> > > I have a module that contains a dash in its name. import severely
> > > dislikes it, and although I can try something like:
> > >
> > > __import__( "my-module" )
> > >
> > > it looks like a wrong thing to do. Any clues as to what is the
> > > proper way of dealing with this?
> >
> >
> > Yes: rename the module to "my_module" or "MyModule" .
>
>
> This is, imvho, a work-around, not a solution. But thanks anyway (I'm
> a little bit too attached to a system forbidding the use of \0 and /
> only).
Well -- you did ask for "the proper way of dealing with" it!
If you're extremely attached to having a non-portable name,
then we can discuss several improper ways to solve the problem.
Python doesn't forbid you using any characters for file names
( which is why __import__ will work ), but Python's grammar
does define what are valid statements and identifiers.
>
> The silly thing is that it is nevertheless possible to import such a
> module (although reloading must be painfil ;))
>
Not at all.
Import is a statement and so the grammar specifies that it be followed
by a valid identifier or comma separated list of identifiers. ( or
a "*" in the "from xxx import *" case. ). Execution of that statement
causes several side effects, one of which is binding those names to
python module objects ( or the objects defined in the modules in the
case of "from xxx import a,b,c" ).
Both __import__() and reload() are functions that take an existing
python object and load a module. __import__ wants a string and reload
wants a module. So you can say:
xxx = __import__( '!@#$%' )
sys.modules[xxx.__name__] = xxx
reload( xxx )
But note that you need to insert the name in sys.modules for
reload to work. But the purpose of sys.modules is to keep
track of already loaded modules so that import doesn't load
them twice. ( subsequent imports just make the namespace
available from the already loaded module. ) and since you
can't say "import !@#$%", you might as well just use __import__()
again rather than reload().
---| Steven D. Majewski (804-982-0831) <sdm7g at Virginia.EDU> |---
---| Department of Molecular Physiology and Biological Physics |---
---| University of Virginia Health Sciences Center |---
---| P.O. Box 10011 Charlottesville, VA 22906-0011 |---
"All operating systems want to be unix,
All programming languages want to be lisp."
More information about the Python-list
mailing list