0

Let us, counterfactually, assume I had a good reason for wanting to make builtin print a static method of some class.

My, apparently wrong, gut feeling was that I need to declare it static doing something like

class sm:
    p = staticmethod(print)

as opposed to

class no_sm:
    p = print

But it seems both work just fine.

a = sm()
b = no_sm()

a.p("hello")
b.p("hello")

prints

hello
hello

Why does it just work and is there any difference between the two?

Related: Why use staticmethod instead of no decorator at all

1 Answer 1

1

for ~most normal functions, they go through a descriptor protocol (__get__) and so they need special decorating when attached to classes in the way you're doing.

take for example:

def f():
    print('hi')

class C:
    f = f

class D:
    f = staticmethod(f)

in this case C().f() errors:

>>> C().f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 0 positional arguments but 1 was given

that's because it goes through:

>>> C.f.__get__(C())()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 0 positional arguments but 1 was given

but you'll notice, that print has no such attribute __get__:

>>> hasattr(print, '__get__')

it even has a different type!

>>> type(print)
<class 'builtin_function_or_method'>
>>> type(f)
<class 'function'>

so the answer is: print (along with other C functions) without special treatment do not participate in the method descriptor protocol so they act as normal callable objects without attachment of self

Sign up to request clarification or add additional context in comments.

1 Comment

So, essentially I picked a bad test case. I did not know that builtins are so fundamentally different from pure Python functions. Another skeleton in Python's cupboard... Anyway, very useful to know. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.