Hey guys, I find bug in Python. If you'll try to file stream using open function you can edit file mode: Watch git: https://gist.github.com/nagayev/7d17ead7b3bc2b06f2445fb5d9122a5c In fact,mode don't changed,so mode shoul be constant like a encoding of the file and raise AttributeError if you'll edit it.
That isn't a bug. Python doesn't protect you from doing the wrong thing, in general. On the other hand, it might be a worthwhile improvement to make it read-only in this case. Especially since, as you point out, other seemingly similar attributes of this object are read-only.
It appears some files like Lib/tokenize.py changes the mode of TextIOWrapper: text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' setting of mode via _PyObject_SetAttrId(wrapper, &PyId_mode, modeobj) is done in some source files too. What I don't understand is since TextIOWrapper doesn't store the mode explicitly, this only adds 'mode' variable to the the object's dict. So why bother setting the mode in all these files?
Changing the value of mode also changes its repr. This seems like a bug to me. It's probably too late to change TextIOWrapper.__repr__(). I think this needs to be discussed on python-dev first. >>> f = open("README.rst") >>> f <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'> >>> f.writable() False >>> f.mode = "w" >>> f.writable() False >>> f <_io.TextIOWrapper name='README.rst' mode='w' encoding='UTF-8'> There's an commented-out code in the initial checkin: https://github.com/python/cpython/commit/4fa88fa0ba35e25ad9be66ebbdaba9aca553dc8b#diff-b67be9e0a41447de808ba3b7099a44a8R2341 /* {"mode", (getter)TextIOWrapper_mode_get, NULL, NULL}, */ TextIOWrapper.__repr__() was updated to include 'mode' in https://github.com/python/cpython/commit/a4815caa7ccf21aa994d0e0eec66873072f0e352 See issue 36271 for a related report. The OP was confused because we don't set mode manually in gzip.open() and bz2.open() (as opposed to what we do in io.open() and tokenize.open())