Which behavior is preferable? (Python embedding)

I am embedding Python in an application. MyClass.nameis a property of the type str:

>>> foo = MyClass()
>>> foo.name
'Default Name'

Should I allow users to do this:

>>> foo.name = 123
>>> foo.name
'123'

or not?

>>> foo.name = 123
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: name must be a string
+3
source share
2 answers

Definitely raise TypeError, not try to force automatically. Usually I would be conservative in saying that something is “pythonic” or not - this is one of those words that really just means “the speaker thinks it's good,” but if it means something in general, it should refer to adhering to Zen of Python , in which case it is saying 12: "In the face of ambiguity, give up the temptation to guess."

, , Decimal s, Fraction s? str repr ? " (" 10 ") " 10 ", Decimal? , , , , , dicts Python? , , , , ?

, , , , Python. (Dictum 8: " , ".) , , , , , . (Dictum 9: " " ). , , , , , - , ( , , !) .

+4

, . , , , python.

class MyClass(object):

  def set_name(self, name):
    self._name = str(name)
  def get_name(self):
    return self._name
  name = propert(get_name, set_name)
+1

Source: https://habr.com/ru/post/1732540/


All Articles