func_code vs. string problem
Filip Dreger
fdreger at amiga.pl
Sat Apr 23 17:30:24 EDT 2005
Uzytkownik "Steven Bethard" <steven.bethard at gmail.com> napisal w
wiadomosci news:QvKdnZAEj5TEKfffRVn-oQ at comcast.com...
> Filip Dreger wrote:
>> I am trying to find a way of executing functions without creating a
>> nested scope, so they can share local and global namespace (even if
>> they are declared in some other module).
>
> Why? Can you explain what the use case is?
I have a large set of objects of a single class - 'actor'. They are
created all at once, and they all live in a sort of container written
in C. The methods of the functions are few and general. One of them is
simply 'act()', that is called by the C program every X seconds (tics,
whatever).
Each object can play 0..N roles, and the roles played by an object
often change during its lifetime. The roles should be played in the
act() method. Also, the roles should be defined in some simple way,
and in an external python file (so adding/removing roles does not
require recompiling of the parts embedded in C).
If I had a magic function 'exec in current scope' I would implement it
like this:
class actor:
def __init__():
self.roles=[]
def act():
for i in self.roles:
exec i in current scope
then the roles would simply be functions defined in any importable
file. For example creating an actor that logs each time it is called
would be as simple as:
import actor
def log():
self.counter+=1
print "called %d times"%self.counter
a=actor.actor()
a.counter=0
a.roles.append(log)
Let me recapitulate (is that the right English word?):
1. I need to keep the definitions of roles in a separate file (they
can not simply be additional methods)
2. I need the roles to have full access to global and local namespace
of the actor object (sometimes they have to change it, and sometimes
they have to use some external modules) - the roles should work like
plugins.
3. I guess I also need a fresh look at the problem. Maybe I am simply
going the wrong way? I am more than willing to change my design, if
someone shows me the light :-)
regards,
Filip Dreger
More information about the Python-list
mailing list