One reason I enjoy programming in Python is its great flexibility.

A few months back I was trying to find some kind of security mechanism for accesses in arbitrary Python objects. The idea was that the access mechanism in the object should be independent from the security policy enforcing.

Here is what I did:

class Access(object):
       def __init__(self, access_fn, permissions):
               self.access_fn   = access_fn
               self.permissions = permissions

       def authenticate(self, credentials):
              print "authenticating ..."

       def __call__(self, credentials, arg):
               self.authenticate(credentials)
               return self.access_fn(arg)

The __call__ is a special method name, which is used to create (or emulate) "callable" objects. An instance of an object in which __call__ is defined, can be "called" as a function. So if acc is an instance of the Access class acc(creds, arg) is equivalent to acc.__call__(creds, arg).

For example:

class FooBar(object):
       def __init__(self, foo, bar):
               self.foo = foo
               self.bar = bar

AccessFoo = Access(lambda arg: arg.foo, None)
foobar = FooBar("foo", "bar")
print AccessFoo(None, foobar)

... simple yet powerfull.