Python function attributes - uses and abuses [closed] Python function attributes - uses and abuses [closed] python python

Python function attributes - uses and abuses [closed]


I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)

class Foo(WebService):    @webmethod    def bar(self, arg1, arg2):         ...

then I can define

def webmethod(func):    func.is_webmethod = True    return func

Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.


I've used them as static variables for a function. For example, given the following C code:

int fn(int i){    static f = 1;    f += i;    return f;}

I can implement the function similarly in Python:

def fn(i):    fn.f += i    return fn.ffn.f = 1

This would definitely fall into the "abuses" end of the spectrum.


You can do objects the JavaScript way... It makes no sense but it works ;)

>>> def FakeObject():...   def test():...     print "foo"...   FakeObject.test = test...   return FakeObject>>> x = FakeObject()>>> x.test()foo