473,761 Members | 2,455 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("fi lename") 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 2154
On Sep 10, 10:52 pm, "bambam" <da...@asdf.asd fwrote:
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("fi lename") 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("fi lename") 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.module s["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("fi lename") 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.module s["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.lonest ar.orgwrote in message
news:ma******** *************** **************@ python.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("fi lename") 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.modul es["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***@holdenwe b.comwrote in message
news:ma******** *************** **************@ python.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("fi lename") 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.modul es["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__(game l['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__(game l['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
12564
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 (most recent call last): File "<string>", line 9, in ? File "imputil.pyc", line 103, in _import_hook File "<string>", line 52, in _import_top_module
6
8911
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 working, this is the problem code: try: import f except: print "not importable"
7
1462
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() <bind obj to func> return func() return wrapper()
0
2766
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 Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel-
0
2725
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 to obtain SHIP_wrap.cpp and SHIP.py; the latter contains the line "import _SHIP". I compile SHIP_wrap.cpp and a bunch of files into a DLL which I have the
16
3115
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 generate an error message ?????
7
2181
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 parenthesis. Example: mymod.py---------------------- def value(): return "hi"
1
3344
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 in-house GCC 3.3.5 setup. Linux rcf-temp3 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:32:02 EDT 2006 x86_64 x86_64 x86_64 GNU/Linux Python 2.3.4 (#1, Sep 26 2006, 17:25:54)
10
2935
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 that? the string could might include name of the module. for example a_string = 'datetime.' + 'today()'
0
9948
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9765
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8770
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6603
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5215
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.