Injecting a global into a defined function??

James Mills prologic at shortcircuit.net.au
Fri Jan 16 05:08:19 CET 2009


On Fri, Jan 16, 2009 at 4:28 AM, Cong Ma <cma at mail.bnu.edu.cn> wrote:
> I'd appreciate your hints on this problem. I'm writing a module in which several
> functions can alter the value of a global variable (I know this sounds evil,
> please forgive me...). What I'm trying to do is to eliminate the "global foo"
> lines in those functions' bodies and to use a decorator for the same task. For
> example:
>
>    @global_injected("SPAM")
>    def foo():
>        ... ...
>
> will have the same effect as
>
>    def foo():
>        global SPAM
>        ... ...
>
> Leaving the evilness of globals aside, I wonder how I can implement this (for
> Python 2.x). I'd like to hear your opinions. Thank you.

This is identical behavior to that of a class/object.

Please explain why you _really_ need to do this ?


class Foo(object):

   def __init__(self):
      self.spam = None

   def foo(self):
      self.spam = "Eggs"

   def bar(self):
      self.spam = "Bacon"

cheers
James



More information about the Python-list mailing list