A basic Namespace metaclass for Python
Suppose that you want to conveniently abuse classes as namespaces. For me, this means avoiding having to splatter
@staticmethod
all over my class definitions; it's both repetitive
make-work and distracting when I'm looking at the source code.
Clearly the solution to this problem is a metaclass to do all of the work for me. Here's one, which is deliberately somewhat simple:
from types import FunctionType
class NSMeta(type): def __new__(meta, cname, bases, cdict): ndict = {} for name, aval in cdict.items(): if type(aval) == FunctionType: aval = staticmethod(aval) ndict[name] = aval return type.__new__(meta, cname, \ bases, ndict) # Inherit from this class: class Namespace(object): __metaclass__ = NSMeta # An example: class uint16(Namespace): def encode(val): return ... def decode(data): return ...
(To fully exhibit my twitch about aesthetics and not repeating myself,
I set up the Namespace
class purely so that 'namespace' classes would
not have to add an extra line to set __metaclass__
. Inheriting from
Namespace
is free, in terms of code layout, since they need to
inherit from something.)
A really superintelligent metaclass would only remap
functions and would peek at what the first argument of every function
was called. If it was 'self', the function would be left alone (and
would thus become a method function); if it was 'cls' (or your preferred
equivalent), the function would be made into a classmethod; otherwise,
the function would be made into a staticmethod.
Writing such a superintelligent metaclass is left as an exercise for the reader.
Update: code in haste, repent slightly later. I have realized that
this metaclass should at least only apply staticmethod
to functions,
since there are sensible uses for non-function things in a namespace
(such as constants). So I've fixed it to do this right.
|
|