473,396 Members | 2,002 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

dynamic import

bry
Hi,
I'm trying to do a dynamic import of a file that has no problems with it, that
is to say I can import it normally, my sys.path is set to the right folder etc.
but my dynamic import code is not working, this is the problem code:

try:
import f[0]
except:
print "not importable"

f[0] returns the name of the file I'm importing, so I suppose this is a typing
problem, should I change f[0] to be some other type?

I've also tried
t = "import " + f[0]
try:
eval(t)
except:
print "not importable"

but I always get "not importable"

Jul 18 '05 #1
6 8888

<br*@itnisk.com> wrote in message
news:ma*************************************@pytho n.org...
Hi,
I'm trying to do a dynamic import of a file that has no problems with it, that is to say I can import it normally, my sys.path is set to the right folder etc. but my dynamic import code is not working, this is the problem code:

try:
import f[0]
except:
print "not importable"

f[0] returns the name of the file I'm importing, so I suppose this is a typing problem, should I change f[0] to be some other type?

I've also tried
t = "import " + f[0]
try:
eval(t)
except:
print "not importable"

but I always get "not importable"


That's because eval evaluates an expression and returns the result. To
execute a statement you need to use exec(t) instead.

Nick
Jul 18 '05 #2
br*@itnisk.com wrote in
news:ma*************************************@pytho n.org:
Hi,
I'm trying to do a dynamic import of a file that has no problems with
it, that is to say I can import it normally, my sys.path is set to the
right folder etc. but my dynamic import code is not working, this is
the problem code:

try:
import f[0]
except:
print "not importable"

f[0] returns the name of the file I'm importing, so I suppose this is
a typing problem, should I change f[0] to be some other type?


No. The import statement takes the name of a module, it doesn't take a
string. For example, instead of:

import sys
print sys.version

you are trying to do the equivalent of:

import "sys"
print "sys".version

You wouldn't expect the second line to work, so why should you expect the
first line to work? If it did work, how would you expect to refer to the
module it imported?

In this case your solution is to use the __import__ builtin. My example
becomes:

module = __import__("sys")
print module.version
Jul 18 '05 #3
br*@itnisk.com wrote:
I'm trying to do a dynamic import of a file that has no problems with it,
that is to say I can import it normally, my sys.path is set to the right
folder etc. but my dynamic import code is not working, this is the problem
code:

try:
import f[0]
except:
print "not importable"

f[0] returns the name of the file I'm importing, so I suppose this is a
typing problem, should I change f[0] to be some other type?

I've also tried
t = "import " + f[0]
try:
eval(t)
except:
print "not importable"

but I always get "not importable"


Let's see.
import f[0] File "<stdin>", line 1
import f[0]
^
SyntaxError: invalid syntax

So python won't accept the [0] stuff here.
f = "os"
import f Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named f

So python doesnt try to resolve f as a variable name but rather as a
literal.
eval("import os") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1
import os
^
SyntaxError: invalid syntax exec "import os"
So the eval() function chokes if you feed it an import statement (actually
any statement).

Quoted from http://docs.python.org/lib/built-in-funcs.html#l2h-23

"""Hints: dynamic execution of statements is supported by the exec
statement."""

Putting it together:
f = ["os"]
exec "import " + f[0]
os

<module 'os' from '/usr/local/lib/python2.3/os.pyc'>

Heureka :-)

Now, did you see how useful Python's tracebacks are and how much information
you lose by a bare try ... except?

try:
...
except ImportError:
...

would have been fine, by the way.

Peter

Jul 18 '05 #4

<br*@itnisk.com> wrote in message
news:ma*************************************@pytho n.org...
Hi,
I'm trying to do a dynamic import of a file that has no problems with it, that is to say I can import it normally, my sys.path is set to the right folder etc. but my dynamic import code is not working, this is the problem code:

try:
import f[0]
except:
print "not importable"


the import statement unfortunately doesn't take a string at
run time. As Duncan says, you need to use the
__import__() builtin. Read up on it in the library
reference (it's the very first entry in the builtins section,)
because there are some considerations in using it that
aren't exactly obvious on first glance.

The other alternative is something like:

exec "import " + f[0]

This will work as well, and it might be a bit clearer, depending
on what you're trying to do.

John Roth
Jul 18 '05 #5
"John Roth" <ne********@jhrothjr.com> writes:

the import statement unfortunately doesn't take a string at
run time. As Duncan says, you need to use the
__import__() builtin. Read up on it in the library
reference (it's the very first entry in the builtins section,)
because there are some considerations in using it that
aren't exactly obvious on first glance.

The other alternative is something like:

exec "import " + f[0]

This will work as well, and it might be a bit clearer, depending
on what you're trying to do.


if one calls the __import__ function with the same argument several times,
will the module be cached inbetween?

Klaus Schilling
Jul 18 '05 #6

<51***************@t-online.de> wrote in message
news:87************@debian.i-did-not-set--mail-host-address--so-shoot-me...
"John Roth" <ne********@jhrothjr.com> writes:

the import statement unfortunately doesn't take a string at
run time. As Duncan says, you need to use the
__import__() builtin. Read up on it in the library
reference (it's the very first entry in the builtins section,)
because there are some considerations in using it that
aren't exactly obvious on first glance.

The other alternative is something like:

exec "import " + f[0]

This will work as well, and it might be a bit clearer, depending
on what you're trying to do.
if one calls the __import__ function with the same argument several times,
will the module be cached inbetween?


You should get the same copy of the module.

John Roth
Klaus Schilling

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Alessandro Crugnola *sephiroth* | last post by:
hi, i have already problems using py2exe.. i'm using python 2.2, wxPython and audiere for a little mp3 player.. once I've build the exe with py2exe, when launching the application: Traceback...
2
by: Chris Hodapp | last post by:
I have seen messages posted about this before, and there is a clear reference to it in the manual, but I have been unable to find a solution. I'm on Slackware 9.1, kernel 2.6.0-test11, using...
1
by: JZ | last post by:
I use Webware and FormKit. I have a problem with dynamic added field to the form. The following code creates one input field and two submit buttons. I would like to add more (up to 4) input fields...
0
by: Vio | last post by:
I have a basic dynamic lib "noddy.so" which I want to 1- embed inside my executable 2- import by embedded python interpreter using an API call. I have two questions: 1- what would be the...
0
by: Bill Davy | last post by:
Hello, I am using SWIG-1.3.24 to make an extension (called SHIP) to Python2.4.1 and then running under IDLE (if that makes any difference) but when I "import SHIP" I get: >>> import SHIP ...
0
by: Bill Davy | last post by:
I am working with MSVC6 on Windows XP. I have created an MSVC project called SHIP I have a file SHIP.i with "%module SHIP" as the first line (file is below). I run SHIP.i through SWIG 1.3.24...
1
by: liam_herron | last post by:
I have compiled my boost-enabled C++ module and have it working when I explicity set my LD_LIBRARY_PATH before invoking the python2.4 interpreter. Now I don't want everyone to have to set this...
7
by: bambam | last post by:
import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global)...
5
by: marcroy.olsen | last post by:
Hi list and python gurus :-) I'm playing with some mod_python and web development. And in me code I need to do som dynamic imports. Right now I just do a: exec 'import '+some_modulename ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.