python / cpython

The Python programming language
https://www.python.org
Other
63.37k stars 30.33k forks source link

metaclasses and __unicode__ #39867

Closed 36c4a441-0683-4fa4-adaf-adc057185e8c closed 20 years ago

36c4a441-0683-4fa4-adaf-adc057185e8c commented 20 years ago
BPO 884064
Nosy @mwhudson, @etrepum

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = 'https://github.com/mwhudson' closed_at = created_at = labels = ['interpreter-core', 'invalid'] title = 'metaclasses and __unicode__' updated_at = user = 'https://bugs.python.org/arundo' ``` bugs.python.org fields: ```python activity = actor = 'mwh' assignee = 'mwh' closed = True closed_date = None closer = None components = ['Interpreter Core'] creation = creator = 'arundo' dependencies = [] files = [] hgrepos = [] issue_num = 884064 keywords = [] message_count = 3.0 messages = ['19822', '19823', '19824'] nosy_count = 3.0 nosy_names = ['mwh', 'bob.ippolito', 'arundo'] pr_nums = [] priority = 'normal' resolution = 'not a bug' stage = None status = 'closed' superseder = None type = None url = 'https://bugs.python.org/issue884064' versions = [] ```

36c4a441-0683-4fa4-adaf-adc057185e8c commented 20 years ago
class Metaklasse (type) :
    def __str__ (cls) :
        return 'string'
    def __unicode__ (cls) :
        return u'unicode'
    def __int__ (cls) :
        return 7

class Klasse :
    __metaclass__ = Metaklasse
    def __str__ (cls) :
        return 'text'
    def __unicode__ (cls) :
        return u'unicodetext'
    def __int__ (cls) :
        return 9

print str(Klasse)

print unicode(Klasse)

print int(Klasse)

print str(Klasse()) print unicode(Klasse()) print int(Klasse())

print unicode(Klasse)

The last print statemant raises an error

Traceback (most recent call last):
  File "Metaklasse.py", line 26, in -toplevel-
    print unicode(Klasse)
TypeError: unbound method __unicode__() must be called 
with Klasse instance as first argument (got nothing 
instead)

unicode() does not use the __unicode__ function of the metaclass. But int() and str() do.

8bb2fe13-d245-4fef-8aa2-70d7108db3c3 commented 20 years ago

Logged In: YES user_id=139309

This is a bug in your implementation, not in Python. On your metaclass, __unicode__ must be a descriptor that looks something like this.

def metamethod(f, doc=None):
....def __get__(ob):
........return f.__get__(ob, ob.__class__)
....return property(__get__, doc=doc)

try it with the metaclass like this:

class Metaclass(type):
....def __unicode__(self):
........return u'metaclass'
....__unicode__ = metamethod(__unicode__)

(btw: to save you the trouble, it works)

mwhudson commented 20 years ago

Logged In: YES user_id=6656

Agree with etrepum.