[Python-Dev] Weird io.OpenWrapper hack to use a function as method

2021年3月31日 05:37:36 -0700

Hi,
The io module provides an open() function. It also provides an
OpenWrapper which only exists to be able to store open as a method
(class or instance method). In the _pyio module, pure Python
implementation of the io module, OpenWrapper is implemented as:
class OpenWrapper:
 """Wrapper for builtins.open
 Trick so that open won't become a bound method when stored
 as a class variable (as dbm.dumb does).
 See initstdio() in Python/pylifecycle.c.
 """
 def __new__(cls, *args, **kwargs):
 return open(*args, **kwargs)
I would like to remove this class which is causing troubles in the PEP
597 implementation, but I don't know how. Simplified problem:
---
def func():
 print("my func")
class MyClass:
 method = func
func() # A
MyClass.method() # B
obj = MyClass()
obj.method() # C
---
With this syntax, A and B work, but C fails with TypeError: func()
takes 0 positional arguments but 1 was given.
If I decorate func() with @staticmethod, B and C work, but A fails
with TypeError: 'staticmethod' object is not callable.
Is OpenWrapper the only way to have a callable object which works in
the 3 variants A, B and C?
A, B and C work if MyClass is modified to use staticmethod:
class MyClass:
 method = staticmethod(func)
Victor
-- 
Night gathers, and now my watch begins. It shall not end until my death.
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/QZ7SFW3IW3S2C5RMRJZOOUFSHHUINNME/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to