Could str () crash in Python?

Are there any cases where str() throws an exception in Python?

+4
source share
3 answers

Yes, it may crash for custom classes:

 >>> class C(object): ... def __str__(self): ... return 'oops: ' + oops ... >>> c = C() >>> str(c) NameError: global name 'oops' is not defined 

It may even crash for some built-in classes such as unicode :

 >>> u = u'\xff' >>> s = str(u) UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128) 
+14
source

Oh sure:

 class A(object): def __str__(self): raise Exception a = A() str(a) 
+8
source

It depends on the object you are calling str() on. Each object can define its own implementation in the __str__() function, and this can easily throw an exception.

Example:

 class A: def __str__(self): raise Exception str(A()) 
+3
source

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


All Articles