New submission from STINNER Victor <[email protected]>:
Currently, static methods created by the @staticmethod decorator are not
callable as regular function. Example:
---
@staticmethod
def func():
print("my func")
class MyClass:
method = func
func() # A: regular function
MyClass.method() # B: class method
MyClass().method() # C: instance method
---
The func() call raises TypeError('staticmethod' object is not callable)
exception.
I propose to make staticmethod objects callable to get a similar to built-in
function:
---
func = len
class MyClass:
method = func
func("abc") # A: regular function
MyClass.method("abc") # B: class method
MyClass().method("abc") # C: instance method
---
The 3 variants (A, B, C) to call the built-in len() function work just as
expected.
If static method objects become callable, the 3 variants (A, B, C) will just
work.
It would avoid the hack like _pyio.Wrapper:
---
class DocDescriptor:
"""Helper for builtins.open.__doc__
"""
def __get__(self, obj, typ=None):
return (
"open(file, mode='r', buffering=-1, encoding=None, "
"errors=None, newline=None, closefd=True)\n\n" +
open.__doc__)
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.
"""
__doc__ = DocDescriptor()
def __new__(cls, *args, **kwargs):
return open(*args, **kwargs)
---
Currently, it's not possible possible to use directly _pyio.open as a method:
---
class MyClass:
method = _pyio.open
---
whereas "method = io.open" just works because io.open() is a built-in function.
See also bpo-43680 "Remove undocumented io.OpenWrapper and _pyio.OpenWrapper"
and my thread on python-dev:
"Weird io.OpenWrapper hack to use a function as method"
https://mail.python.org/archives/list/[email protected]/thread/QZ7SFW3IW3S2C5RMRJZOOUFSHHUINNME/
----------
components: Library (Lib)
messages: 389905
nosy: vstinner
priority: normal
severity: normal
status: open
title: Make function wrapped by staticmethod callable
versions: Python 3.10
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue43682>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com