Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10998

how to dynamically generate __name__ for an object?

Date 2011-08-06 21:06 -0600
Subject how to dynamically generate __name__ for an object?
From Eric Snow <ericsnowcurrently@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2004.1312686417.1164.python-list@python.org> (permalink)

Show all headers | View raw


Thought I knew how to provide a dynamic __name__ on instances of a
class.  My first try was to use a non-data descriptor:

# module base.py

class _NameProxy(object):
    def __init__(self, oldname):
        self.oldname = oldname
    def __get__(self, obj, cls):
        if obj is None:
            return self.oldname
        if "__name__" not in obj.__dict__:
            return str(obj.__context__)
        return obj.__name__

class _BaseMeta(type):
    def __init__(cls, name, bases, namespace):
        cls.__name__ = _NameProxy(name)

class Base(object):
    __metaclass__ = _BaseMeta


$ python _base.py
Traceback (most recent call last):
  ...
  File "/usr/local/lib/python2.4/site-packages/base.py", line xx, in __init__
    cls.__name__ = _NameProxy(name)
TypeError: Error when calling the metaclass bases
    can only assign string to Base.__name__, not '_NameProxy'


Needless to say I was surprised.  After looking in typeobject.c, I
believe that __name__ must be a string where classes are concerned[1].
 So if I want all my instances to have a __name__ attribute, and for
it to be dynamically provided if it isn't set on the instance, what
are my options?  Or maybe I did something wrong and it should work as
I expected?

-eric


[1] http://hg.python.org/cpython/file/default/Objects/typeobject.c#l244

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

how to dynamically generate __name__ for an object? Eric Snow <ericsnowcurrently@gmail.com> - 2011-08-06 21:06 -0600
  Re: how to dynamically generate __name__ for an object? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-07 14:47 +1000
    Re: how to dynamically generate __name__ for an object? Eric Snow <ericsnowcurrently@gmail.com> - 2011-08-07 02:05 -0600
  Re: how to dynamically generate __name__ for an object? Fuzzyman <fuzzyman@gmail.com> - 2011-08-10 07:48 -0700
    Re: how to dynamically generate __name__ for an object? Ian Kelly <ian.g.kelly@gmail.com> - 2011-08-10 09:25 -0600
      Re: how to dynamically generate __name__ for an object? Fuzzyman <fuzzyman@gmail.com> - 2011-08-10 09:38 -0700
    Re: how to dynamically generate __name__ for an object? Eric Snow <ericsnowcurrently@gmail.com> - 2011-08-10 10:54 -0600

csiph-web