◐ Shell
clean mode source ↗

bpo-43510: Remove _pyio.OpenWrapper class by methane · Pull Request #25107 · python/cpython

eryksun

# Emit the EncodingWarning for the caller.
if "b" not in mode:
encoding = text_encoding(encoding)
return open(file, mode, buffering, encoding, *args, **kwargs)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you checking this here instead of leaving it up to the open call in order to raise the warning at the right stack level?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. text_encoding() is used for it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, so this is just a particular problem in an unusual case of a proxy call that needs to bring the text_encoding call forward, with special handling such as checking if "b" not in mode.

@vstinner

OpenWrapper is really a weird beast. I don't know other functions which are defined this way. Can't we decorate def open with @staticmethod instead?

The io module doesn't use this hack: OpenWrapper is just an alias to open.

$ python3
Python 3.9.2 (default, Feb 20 2021, 00:00:00) 
>>> import io
>>> io.OpenWrapper
<built-in function open>
>>> io.OpenWrapper is io.open
True

@methane

OpenWrapper is really a weird beast. I don't know other functions which are defined this way. Can't we decorate def open with @staticmethod instead?

Nice idea.

@methane methane changed the title bpo-43510: PEP 597: OpenWrapper emits EncodingWarning for the caller bpo-43510: Remove _pyio.OpenWrapper class

Mar 31, 2021

@methane

Oh, test is failing...

======================================================================
ERROR: test_read (test.test_univnewlines.PyTestCRLFNewlines)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/work/cpython/cpython/Lib/test/test_univnewlines.py", line 51, in setUp
    with self.open(os_helper.TESTFN, self.WRITEMODE) as fp:
TypeError: 'staticmethod' object is not callable

@vstinner

@vstinner

@eryksun

Maybe define open as a classmethod in a dummy class and set the bound method as global open. Or continue to define open as a function, and set OpenWrapper as a functools.partial instance, since it's builtin and doesn't insert a stack frame.