A basic Namespace metaclass for Python

June 22, 2011

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.

Written on 22 June 2011.
« Abusing Python classes as namespaces
The ZFS opacity problem and its effect on manageability »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Wed Jun 22 01:51:27 2011
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.