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

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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

Answer*

Draft saved
Draft discarded
Cancel

lang-py

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