This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: missing __enter__ + __getattr__ forwarding
Type: Stage:
Components: Library (Lib) Versions: Python 2.5
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: georg.brandl Nosy List: georg.brandl, ocean-city
Priority: high Keywords:

Created on 2006-10-20 15:17 by ocean-city, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
a.py ocean-city, 2006-10-20 15:17 the script to reproduce problem
a.patch ocean-city, 2006-10-20 15:18 simply solve only codecs.open
Messages (2)
msg30327 - (view) Author: Hirokazu Yamamoto (ocean-city) * (Python committer) Date: 2006-10-20 15:17
Hello. I encountered some unexpected behavior on "with"
statement.

First, please run attached "a.py" file.

# traditional way
<open file 'a.txt', mode 'wb' at 0x009373C8> shift_jis
<type 'instance'> True
# with statement
<open file 'a.txt', mode 'wb' at 0x009373C8> None <type
'file'> False
Traceback (most recent call last):
  File "R:\a.py", line 15, in <module>
    test(io)
  File "R:\a.py", line 8, in test
    io.write(u"あいうえお")
UnicodeEncodeError: 'ascii' codec can't encode
characters in position 0-4: ordin
al not in range(128)

"traditional way" runs as expected, but "with
statement" crashes. This happens because....

  1. codecs.open returns codecs.StreamReaderWriter
  2. codecs.StreamReaderWriter defines __getattr__
     like this.

    def __getattr__(self, name,
                    getattr=getattr):

        """ Inherit all other methods from the
            underlying stream.
        """
        return getattr(self.stream, name)

  3. But codecs.StreamReaderWriter doesn't have its
     __enter__ definition, so 

    srw = StreamReaderWriter(stream, ...
    srw.__enter__() # actually calls stream.__enter__
                      which returns stream not srw
                      via __getattr__

     And more worse, with statement doesn't complain
     StreamReaderWriter (currently) doesn't support
     context manager.

Is this intended behavior? If not, only this problem
can be solved by attached "a.patch". I greped library
files, I found many __getattr__ without __enter__...

msg30328 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-10-29 14:47
Logged In: YES 
user_id=849994

This is a duplicate of #1586513 which has been fixed today.
History
Date User Action Args
2022-04-11 14:56:20adminsetgithub: 44152
2006-10-20 15:17:13ocean-citycreate