468,284 Members | 1,610 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,284 developers. It's quick & easy.

Re: Storing a function

En Sun, 25 May 2008 18:00:12 -0300, Kuros <ku*********@gmail.comescribió:
Hi,
Hoping I could get some help with a python question.

I want to be able to store the code for a single function in a .py file,
such as:

def test():
print "Test"

From within a Python script, I would like to be able to get a handler so I
can do something like:

handler.test()
The "handler" is called a "module" and is created from the .py file by using import...
I want to be able to store the handlers in a blob in a SQLite DB.
So store the .py file...
Essentially, I want to store a compiled version of a function. I have tried
using compile() and exec, and while it sort of works, it seems to import the
code into the global namespace. I can do:

x = compile(file.read(), "<x>", 'exec')
exec x
test()

and it calls test, but I may have several functions with the same name, all
read from different files. So I need to be able to do handler.test().
If you don't want to store the .py, store the compiled module .pyc
If you still want to create and manage your own fake version of modules, use an explicit namespace:

ns = {}
compiled = compile(...)
exec compiled in ns
test = ns['test']
test()

--
Gabriel Genellina

Jun 27 '08 #1
0 562

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Kay | last post: by
20 posts views Thread by Martin Jørgensen | last post: by
reply views Thread by Calvin Spealman | last post: by
reply views Thread by NPC403 | last post: by
2 posts views Thread by MrBee | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.