Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > import from a string

Reply
Thread Tools

import from a string

 
 
iu2
Guest
Posts: n/a
 
      11-03-2009
Hi,

Having a file called funcs.py, I would like to read it into a string,
and then import from that string.
That is instead of importing from the fie system, I wonder if it's
possible to eval the text in the string and treat it as a module.

For example

with file('funcs.py') as f: txt = r.read()
string_import(txt, 'funcs') # is string_import possible?

to have now a module called funcs with the functions defined in
funcs.py.

Thanks

 
Reply With Quote
 
 
 
 
Matt McCredie
Guest
Posts: n/a
 
      11-03-2009
iu2 <israelu <at> elbit.co.il> writes:

>
> Hi,
>
> Having a file called funcs.py, I would like to read it into a string,
> and then import from that string.
> That is instead of importing from the fie system, I wonder if it's
> possible to eval the text in the string and treat it as a module.
>
> For example
>
> with file('funcs.py') as f: txt = r.read()
> string_import(txt, 'funcs') # is string_import possible?
>
> to have now a module called funcs with the functions defined in
> funcs.py.


You can do something like this:

import types
import sys

mymodule = types.ModuleType("mymodule", "Optional Doc-String")

with file('funcs.py') as f:
txt = f.read()
exec txt in globals(), mymodule.__dict__
sys.modules['mymodule'] = mymodule


Note that you shouldn't exec untrusted code.
You might also look at the __import__ funciton, which can import by python path.
You might also look at the imp module.

Matt

 
Reply With Quote
 
 
 
 
iu2
Guest
Posts: n/a
 
      11-03-2009
On Nov 3, 7:49*pm, Matt McCredie <(E-Mail Removed)> wrote:
> iu2 <israelu <at> elbit.co.il> writes:
>
>
>
> > Hi,

>
> > Having a file called funcs.py, I would like to read it into a string,
> > and then import from that string.
> > That is instead of importing from the fie system, I wonder if it's
> > possible to eval the text in the string and treat it as a module.

>
> > For example

>
> > with file('funcs.py') as f: txt = r.read()
> > string_import(txt, 'funcs') *# is string_import possible?

>
> > to have now a module called funcs with the functions defined in
> > funcs.py.

>
> You can do something like this:
>
> import types
> import sys
>
> mymodule = types.ModuleType("mymodule", "Optional Doc-String")
>
> with file('funcs.py') as f:
> * * txt = f.read()
> exec txt in globals(), mymodule.__dict__
> sys.modules['mymodule'] = mymodule
>
> Note that you shouldn't exec untrusted code.
> You might also look at the __import__ funciton, which can import by python path.
> You might also look at the imp module.
>
> Matt


Thanks, it seems simpler than I thought.
I don't fully understand , though, the exec statement, how it causes
the string execute in the context of mymodule.
 
Reply With Quote
 
Gabriel Genellina
Guest
Posts: n/a
 
      11-04-2009
En Tue, 03 Nov 2009 17:36:08 -0300, iu2 <(E-Mail Removed)> escribiˇ:
> On Nov 3, 7:49 pm, Matt McCredie <(E-Mail Removed)> wrote:
>> iu2 <israelu <at> elbit.co.il> writes:
>>
>> > Having a file called funcs.py, I would like to read it into a string,
>> > and then import from that string.
>> > That is instead of importing from the fie system, I wonder if it's
>> > possible to eval the text in the string and treat it as a module.


>> mymodule = types.ModuleType("mymodule", "Optional Doc-String")
>> with file('funcs.py') as f:
>> txt = f.read()
>> exec txt in globals(), mymodule.__dict__
>> sys.modules['mymodule'] = mymodule

>
> Thanks, it seems simpler than I thought.
> I don't fully understand , though, the exec statement, how it causes
> the string execute in the context of mymodule.


Sometimes you don't even require a module, and this is simpler to
understand. Suppose you have a string like this:

txt = """
def foo(x):
print 'x=', x

def bar(x):
return x + x
"""

you may execute it:

py> namespace = {}
py> exec txt in namespace

The resulting namespace contains the foo and bar functions, and you may
call them:

py> namespace.keys()
['__builtins__', 'foo', 'bar']
py> namespace['foo']('hello')
x= hello

exec just executes the string using the given globals dictionary as its
global namespace. Whatever is present in the dictionary is visible in the
executed code as global variables (none in this example). The global names
that the code creates become entries in the dictionary. (foo and bar;
__builtins__ is an implementation detail of CPython). You may supply
separate globals and locals dictionaries.

--
Gabriel Genellina

 
Reply With Quote
 
iu2
Guest
Posts: n/a
 
      11-04-2009
On Nov 4, 3:10*am, "Gabriel Genellina" <(E-Mail Removed)> wrote:
> En Tue, 03 Nov 2009 17:36:08 -0300, iu2 <(E-Mail Removed)> escribiˇ:
>
>
>
>
>
> > On Nov 3, 7:49 pm, Matt McCredie <(E-Mail Removed)> wrote:
> >> iu2 <israelu <at> elbit.co.il> writes:

>
> >> > Having a file called funcs.py, I would like to read it into a string,
> >> > and then import from that string.
> >> > That is instead of importing from the fie system, I wonder if it's
> >> > possible to eval the text in the string and treat it as a module.
> >> mymodule = types.ModuleType("mymodule", "Optional Doc-String")
> >> with file('funcs.py') as f:
> >> * * txt = f.read()
> >> exec txt in globals(), mymodule.__dict__
> >> sys.modules['mymodule'] = mymodule

>
> > Thanks, it seems simpler than I thought.
> > I don't fully understand , though, the exec statement, how it causes
> > the string execute in the context of mymodule.

>
> Sometimes you don't even require a module, and this is simpler to *
> understand. Suppose you have a string like this:
>
> txt = """
> def foo(x):
> * *print 'x=', x
>
> def bar(x):
> * *return x + x
> """
>
> you may execute it:
>
> py> namespace = {}
> py> exec txt in namespace
>
> The resulting namespace contains the foo and bar functions, and you may *
> call them:
>
> py> namespace.keys()
> ['__builtins__', 'foo', 'bar']
> py> namespace['foo']('hello')
> x= hello
>
> exec just executes the string using the given globals dictionary as its *
> global namespace. Whatever is present in the dictionary is visible in the *
> executed code as global variables (none in this example). The global names *
> that the code creates become entries in the dictionary. (foo and bar; *
> __builtins__ is an implementation detail of CPython). You may supply *
> separate globals and locals dictionaries.
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -


Thanks for the explanation.
What happens if both global and local dictionaries are supplied: where
are the newly created entities created? In the local dict?


 
Reply With Quote
 
Gabriel Genellina
Guest
Posts: n/a
 
      11-04-2009
En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <(E-Mail Removed)> escribiˇ:
> On Nov 4, 3:10 am, "Gabriel Genellina" <(E-Mail Removed)> wrote:


>> txt = """
>> def foo(x):
>> print 'x=', x
>>
>> def bar(x):
>> return x + x
>> """
>>
>> py> namespace = {}
>> py> exec txt in namespace
>> py> namespace.keys()
>> ['__builtins__', 'foo', 'bar']
>> py> namespace['foo']('hello')
>> x= hello


> What happens if both global and local dictionaries are supplied: where
> are the newly created entities created? In the local dict?


The amazing thing about Python is how easy is to experiment in the
interpreter.
Just see it by yourself!

--
Gabriel Genellina

 
Reply With Quote
 
Terry Reedy
Guest
Posts: n/a
 
      11-04-2009
Gabriel Genellina wrote:
> En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <(E-Mail Removed)> escribiˇ:
>> On Nov 4, 3:10 am, "Gabriel Genellina" <(E-Mail Removed)> wrote:

>
>>> txt = """
>>> def foo(x):
>>> print 'x=', x
>>>
>>> def bar(x):
>>> return x + x
>>> """
>>>
>>> py> namespace = {}
>>> py> exec txt in namespace
>>> py> namespace.keys()
>>> ['__builtins__', 'foo', 'bar']
>>> py> namespace['foo']('hello')
>>> x= hello

>
>> What happens if both global and local dictionaries are supplied: where
>> are the newly created entities created? In the local dict?

>
> The amazing thing about Python is how easy is to experiment in the
> interpreter.
> Just see it by yourself!


Hint: they are created in the same namespace they always are (ignoring
nested functions and nonlocal namespaces). But I agree with Gabriel:
just try it. n1,n2={},{}; exec....

Terry Jan Reedy


 
Reply With Quote
 
iu2
Guest
Posts: n/a
 
      11-05-2009
On Nov 4, 8:51*pm, Terry Reedy <(E-Mail Removed)> wrote:
> Gabriel Genellina wrote:
> > En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <(E-Mail Removed)> escribiˇ:
> >> On Nov 4, 3:10 am, "Gabriel Genellina" <(E-Mail Removed)> wrote:

>
> >>> txt = """
> >>> def foo(x):
> >>> * *print 'x=', x

>
> >>> def bar(x):
> >>> * *return x + x
> >>> """

>
> >>> py> namespace = {}
> >>> py> exec txt in namespace
> >>> py> namespace.keys()
> >>> ['__builtins__', 'foo', 'bar']
> >>> py> namespace['foo']('hello')
> >>> x= hello

>
> >> What happens if both global and local dictionaries are supplied: where
> >> are the newly created entities created? In the local dict?

>
> > The amazing thing about Python is how easy is to experiment in the
> > interpreter.
> > Just see it by yourself!

>
> Hint: they are created in the same namespace they always are (ignoring
> nested functions and nonlocal namespaces). But I agree with Gabriel:
> just try it. n1,n2={},{}; exec....
>
> Terry Jan Reedy- Hide quoted text -
>
> - Show quoted text -


n2
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
to use import java.lang.* or import java.lang.Math or none at all? JPractitioner Java 13 02-24-2006 08:48 PM
XML Schema question - does "import" import elements? Vitali Gontsharuk XML 2 08-25-2005 07:33 PM
IMPORT STATIC; Why is "import static" file scope? Why not class scope? Paul Opal Java 12 10-10-2004 11:01 PM
GTK import doesn't import first time Dennis Python 2 08-18-2003 10:00 PM
import/from import question Artur M. Piwko Python 1 07-02-2003 07:04 PM



Advertisments