namespaces in python

Jonathan Hogg jonathan at onegoodidea.com
Tue Jul 16 07:06:29 EDT 2002


On 16/7/2002 8:32, in article w_PY8.102605$xy.35029121 at twister.socal.rr.com,
"Jeff Davis" <jdavis at empires.org> wrote:

> Is there a way to put functions and variables in a different namespace
> without putting it in a seperate file or instantiating a new object? Is
> there a way to have static methods that don't require instantiating the
> object first?

If you're using Python 2.2 with metaclasses, you can do this:

>>> class namespace( object ):
...     def __init__( self, name, bases, dict ):
...         self.__name = name
...         self.__dict__.update( dict )
...     def __repr__( self ):
...         return '<namespace %s>' % self.__name
... 
>>> 
>>> class foo:
...     __metaclass__ = namespace
...     def hello( name='World' ):
...         print 'Hello', name
...     CONSTANT = 5
... 
>>> foo
<namespace foo>
>>> foo.hello()
Hello World
>>> foo.hello( 'Jonathan' )
Hello Jonathan
>>> foo.CONSTANT
5
>>> 

Note that foo is not actually a "class" as such. It's an instance of
'namespace', which isn't a proper type. This could also be extended to do
something useful with the bases so that you can inherit from other
namespaces.

Metaclasses allow you to pull all manner of tricks with 'class' ;-)

[As an aside, while I know this is a horrible idea, it would be ultra-cool
to be able to use syntax like:

    <thing> <name> ( [<base> ...] ):
        <defn>
        ...

to mean:

    class <name> ( [<base> ...] ):
        __metaclass__ = <thing>
        <defn>
        ...

so that you could just have written for the above:

>>> namespace foo:
...     def hello( name='World' ):
...         print 'Hello', name
...

I can think of nummerous other examples like this one.]

I'll-make-Guido-timothy-the-day-he-introduced-metaclasses-<wink>-ly y'rs,

Jonathan




More information about the Python-list mailing list