Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

1 of 2

Python setattr vs __setattr__ UnicodeEncodeError

I know that we have to use setattr method when we are outside of an object. However, I have troubles calling setattr with unicode key leading me to use __setattr__ directly.

class MyObject(object): def __init__(self): self.__dict__["properties"] = dict() def __setattr__(self, k, v): self.properties[k] = v obj = MyObject()

And I get the following content of obj.properties:

  • setattr(obj, u"é", u"à"): raise UnicodeEncodeError
  • setattr(obj, "é", u"à"): {'\xc3\xa9': u'\xe0'}
  • obj.__setattr__(u"é", u"à"): {u'\xe9': u'\xe0'}

I don't understand why Python is behaving with these differences

lang-py

AltStyle によって変換されたページ (->オリジナル) /