New submission from Leo: The nametuple function creates classes dynamically. The caller must provide the class name thus overriding any existing object name. An overridden object may be garbage-collected or survive depending on its reference count.
While this behavior is not new to Python, I am unaware of a simple function with such an awkward side effect. One might consider this a feature rather than a bug thus shifting responsibility for carefully passing suitable class names to nametuple. However, I believe nametuple should raise an exception if the provided name would override an existing name. If needed, this behavior could be made customizable by a keyword argument override defaulting to False. Consequently, the caller would have to delete the object under that name explicitly before calling nametuple. This behavior would increase code clarity and eliminate´ a source of subtle errors. The code example given below shows the survival of a pre-existing class due to an instance linked to it. As a consequence, two different classes with the same name exist. Only the posterior is, however, bound to the __main__ namespace. The prior is no longer known to that namespace potentially breaking remote parts of the code. In [1]: from collections import namedtuple In [2]: AB=namedtuple('AB', ('a','b')) In [3]: ab=AB(4,9) In [4]: type(ab) Out[4]: __main__.AB In [6]: AB=namedtuple('AB', ('c','d')) In [7]: type(ab) Out[7]: __main__.AB In [8]: ab2=AB(16,25) In [9]: type(ab2) Out[9]: __main__.AB In [10]: type(ab) Out[10]: __main__.AB In [11]: ab Out[11]: AB(a=4, b=9) In [12]: ab2 Out[12]: AB(c=16, d=25) ---------- components: Library (Lib) messages: 228641 nosy: fhaxbo...@googlemail.com priority: normal severity: normal status: open title: namedtuple: raise an exception when the given class name would override an existing name type: behavior versions: Python 3.4 _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue22563> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com