func_code vs. string problem
Steven Bethard
steven.bethard at gmail.com
Sat Apr 23 17:44:30 EDT 2005
Filip Dreger wrote:
> 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)
Any reason you can't define it like:
class actor(object):
def __init__(self):
self.roles = []
def act(self):
for role_func in self.roles:
role_func(self)
And then write your other modules like:
import actor
def log(self):
self.counter += 1
print "called %d times"%self.counter
a = actor.actor()
a.counter = 0
a.roles.append(log)
The only real difference here is that log is basically declared as an
instance method. So if you need to update actor.actor state, you simply
modify the self object.
> 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.
By importing actor, they have full access to the global namespace of the
actor.actor object, by simply accessing the actor module attributes.
So the issue here is really about full *local* namespace access. Do you
really need *full* local namespace access? Why isn't access to the
actor.actor instance sufficient?
STeVe
More information about the Python-list
mailing list