473,397 Members | 2,077 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,397 software developers and data experts.

function to do dynamic import?

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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.

Steve.

---
>>def gim():
.... exec "import gamel"
....
>>gim()
sys.modules["gamel"]
<module 'gamel' from 'c:\gamel.pyc'>
>>>gamel
NameError: name 'gamel' is not defined
>>>exec "import gamel"
gamel
<module 'gamel' from 'c:\gamel.pyc'>
Sep 11 '07 #1
7 2133
On Sep 10, 10:52 pm, "bambam" <da...@asdf.asdfwrote:
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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.

Steve.


(snipped)

This was recently discussed:

http://groups.google.com/group/comp....fcdf49710cb833

--
Hope this helps,
Steven

Sep 11 '07 #2
bambam wrote:
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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.

Steve.

---
>>>def gim():
... exec "import gamel"
...
All you have done in this function is bind the module to the name gamel
within the scope of the function. As soon as the function exits, the
module goes out of scope. If you want to use it externally, return the
module.

def: gim():
import gamel
return gamel
>>>gim()
This will have to change to

gamel = gim()

and the rest should work as expected.
>>>sys.modules["gamel"]
<module 'gamel' from 'c:\gamel.pyc'>
>>>gamel
NameError: name 'gamel' is not defined
>>>exec "import gamel"
gamel
<module 'gamel' from 'c:\gamel.pyc'>
Sep 11 '07 #3
bambam wrote:
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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.
There's not much wrong with doing this, since it gives you the best of
both worlds. But you mean sys.modules["filename"], don't you?
>>>def gim():
... exec "import gamel"
...
>>>gim()
sys.modules["gamel"]
<module 'gamel' from 'c:\gamel.pyc'>
>>>gamel
NameError: name 'gamel' is not defined
>>>exec "import gamel"
gamel
<module 'gamel' from 'c:\gamel.pyc'>

Whoa there! There's a lot of difference between "importing a module
inside a function" and "executing an import statement inside a function".

If you want to do dynamic imports then the __import__ function is what
you need. Trying to use exec like that is a bad idea unless you clearly
understand the relationship between the different namespaces involved.
In fact, trying to use exec at all is a bad idea until you understand
Python better, and even then it's not often a terrific idea.

Think of exec more as a hack of last resort than the first tool to reach
for to solve a problem.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Sep 11 '07 #4

"J. Cliff Dyer" <jc*@sdf.lonestar.orgwrote in message
news:ma*************************************@pytho n.org...
bambam wrote:
>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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.

Steve.

---
>>>>def gim():
>
... exec "import gamel"
...
All you have done in this function is bind the module to the name gamel
within the scope of the function. As soon as the function exits, the
module goes out of scope. If you want to use it externally, return the
module.

def: gim():
import gamel
return gamel
>>>>gim()
>
This will have to change to

gamel = gim()

and the rest should work as expected.
>>>>sys.modules["gamel"]
>
<module 'gamel' from 'c:\gamel.pyc'>
>>>>gamel
>
NameError: name 'gamel' is not defined
>>>>exec "import gamel"
gamel
>
<module 'gamel' from 'c:\gamel.pyc'>
def: gim():
import gamel
return gamel

Unfortunately, it needs to do dynamic import: I can't list
all of the possible import modules because they are unknown
until runtime.

Steve.
Sep 12 '07 #5

"Steve Holden" <st***@holdenweb.comwrote in message
news:ma*************************************@pytho n.org...
bambam wrote:
>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) scope.

Questions:
(1) Where can I read an explanation of this?
(2) Is there a work around?

BTW, sys.modules("filename") shows that the module is
loaded, I just don't know how to use it when loaded that
way. Also, if I import again at the global scope, the module
name becomes available.
There's not much wrong with doing this, since it gives you the best of
both worlds. But you mean sys.modules["filename"], don't you?
>>>>def gim():
... exec "import gamel"
...
>>>>gim()
sys.modules["gamel"]
<module 'gamel' from 'c:\gamel.pyc'>
>>>>gamel
NameError: name 'gamel' is not defined
>>>>exec "import gamel"
gamel
<module 'gamel' from 'c:\gamel.pyc'>
Whoa there! There's a lot of difference between "importing a module inside
a function" and "executing an import statement inside a function".

If you want to do dynamic imports then the __import__ function is what you
need. Trying to use exec like that is a bad idea unless you clearly
understand the relationship between the different namespaces involved. In
fact, trying to use exec at all is a bad idea until you understand Python
better, and even then it's not often a terrific idea.

Think of exec more as a hack of last resort than the first tool to reach
for to solve a problem.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
Yes, sys.modules["filename"], unfortunately, same mistake
made already 4 or 5 times before I typed this, and still hadn't
learned...many years working in an environment where the
distinction was not important. Sorry.

def gim(self):
for gamel in self.gamel_list:
__import__(gamel['file'])

Works as hoped for. I did a web search for 'dynamic import' and
the only examples I found used exec.

Thanks

Steve.
Sep 12 '07 #6
bambam wrote:
[...]
def gim(self):
for gamel in self.gamel_list:
__import__(gamel['file'])

Works as hoped for. I did a web search for 'dynamic import' and
the only examples I found used exec.

Thanks
Cool. You're getting there!

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Sep 12 '07 #7
Am Wed, 12 Sep 2007 11:54:51 +1000 schrieb bambam:
def gim():
exec "global gamel"
exec "import gamel"

Unfortunately, does not have the desired effect.
Steve.
Both statements have to be part of a single exec:

def gim():
modulename = "gamel" # determined at runtime
exec "global %s; import %s" % (modulename, modulename)

It may work, but it is still a bad idea to create global variables with a
name not known until runtime.

Peter
Sep 12 '07 #8

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...
6
by: bry | last post by:
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...
7
by: vegetax | last post by:
I i need a decorator that adds a local variable in the function it decorates, probably related with nested scopes, for example: def dec(func): def wrapper(obj = None): if not obj : obj = Obj()...
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...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() : global math # necessary ?????? else next line...
7
by: gabriel.becedillas | last post by:
I have a module that defines a variable with a constant value and now I need to make that value dynamic, without affecting module clients. In other words, I need to call a function witout using...
1
by: kickslop | last post by:
Clearly I am doing something braindead here with psycopg 1.1.21 (psycopg2 is not an option). Any ideas? I get the same results when I build it with Red Hat's GCC 3.4.6 setup as well as our...
10
by: james_027 | last post by:
hi, i have a function that I could like to call, but to make it more dynamic I am constructing a string first that could equivalent to the name of the function I wish to call. how could I do...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
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.