New module for method level access modifiers

TimeHorse darklord at timehorse.com
Tue Oct 23 19:08:19 CEST 2007


I have started work on a new module that would allow the decoration of
class methods to restrict access based on calling context.
Specifically, I have created 3 decorators named public, private and
protected.

These modifiers work as follows:

Private: A private method can only be called from a method defined in
the same class as the called method.

Protected: A protected method can only be called from a method defined
in the same or class derived from the called method's class.

Public: No access restrictions (essentially a no-op).

Programmers with a C++ or Java background will be familiar with these
concepts in those languages; these decorators attempt to emulate their
behavior

Bugs:

1)	These decorators will not tolerate other decorators because they
examine the call stack in order to determine the caller's frame.  A
second decorator, either before or after the access decorator will
insert a stack frame, which the current version of these decorators
cannot handle.  Making sure decorators set their wrapper functions
__name__, __doc__ and append to its dictionary would be required at
least for interoperability.

2)	As noted, staticmethod and classmethod cannot be handled by the
access decorators, not only because they are decorators themselves,
but because the current access decorators require access to an
instance of the class (self) in order to do method resolution.
classmethod support could probably be added without too much
difficulty but staticmethods, because they have no self or cls, would
be difficult.

3)	Friend classes, as defined in C++.  These would probably be defined
as a class-level list of classes that may have private/protected
access to the given class's internals.  This should not be too hard to
add.

4)	Decorators for member variables -- these decorators can already be
applied to get_* and set_* methods for properties.  Overriding
__getattr__ may be a better solution for attribute access, however.

Source available at: http://starship.python.net/crew/timehorse/access.py

Jeffrey




More information about the Python-list mailing list