Negroup - wrote:
> Hi all! I'm here again with a question about introspection.
> 
> My module stores a set of functions. I need to know, from another
> script, if a particular function of this module "is enabled" (it
> means, if it shall be executed by the caller script). I looked for
> some introspective builtin/function, but I didn't find anything useful
> (except func_globals, func_dict, func_code, etc, that don't help in my
> case).
> 
> This is my solution:
> 
> mymodule.py
> def f1():
>   pass
> def f2():
>   pass
> 
> setattr(f1, 'enabled', True)
> setattr(f2, 'enabled', False)

This seems OK to me. You don't need setattr(), you can set the attribute 
directly:
f1.enabled = True

Adding attributes to functions is only supported in recent versions of Python 
so this is not a good solution if you need to work with older versions.

>From your later description I see that you want to do this dynamically and the 
>set of enabled functions is really a property of the client, not of the 
>function itself. You have a list of headers and you want to apply all the 
>functions that match the headers. I would look for a way to have the client 
>figure out which functions to apply. Maybe keep a list of the headers and use 
>it to filter the list of functions. 

For example if fns is the list of functions and headers is a list (or set) of 
header names matching the functions you could do
for fn in fns:
  if fn.__name__ in headers:
    fn()

This keeps the responsibility for executing the correct functions with the 
client which seems like the right place to me.

Also if it matters, your solution is not thread-safe because it uses global 
state (the enabled flag in the function). If you have multiple threads doing 
this you will get errors.

Kent

-- 
http://www.kentsjohnson.com

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to