Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behavior in Python

What undefined behavior does Python have? Undefined meaning not in the specification of the language. The only example I know of is modifying a sequence while iterating through it. Before learning about that I used to think that Python didn't have undefined behavior, so I assume it is extremely rare.

like image 575
RedKnite Avatar asked Jun 20 '26 19:06

RedKnite


1 Answers

Here are two:

  • Garbage collection
  • Ordered dictionaries in Python 3.6

I would argue that garbage collection falls into this category. The main Python implementation (e.g. CPython) uses reference counting for garbage collection, but this is not mandated by the language spec.

Further, you cannot rely on a variable being garbage collected (and therefore "cleaned up") at any particular point in Python.

Consider this:

f = open("file.txt").read()

This is pretty common in new-to-python code, and seems safe enough, but there is no explicit .close() call on the opened file object. When the object is destroyed, .close() is called implicitly. Because of the way CPython works this almost always gets destroyed in a timely manner and this ends up being OK in practice. But for other python interpreters this many not be the case and you could end up with dangling file objects. This is why you always see folks saying it is safer to do

with open("file.txt") as fl:
   f = fl.read()

because now the closing of the object is not only explicit, but is guaranteed to happen at a particular line of code.


In Python 3.6, dictionaries were ordered as in implementation detail in CPython. It was not mandated by the spec, but people started to rely on this undefined behavior which would cause problems for users of other python interpreters, so in Python 3.7 they made ordered dictionaries part of the spec.

like image 92
SethMMorton Avatar answered Jun 23 '26 18:06

SethMMorton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!