Skip to content

Call built-in method of object instance, lost self param? #132299

Description

@A4-Tacks
>>> class Foo:
...  f=print
...
>>> Foo.f(2)
2
>>> Foo().f(2)
2
>>> def f(*args): print(*args)
...
>>> class Foo:
...  f=f
...
>>> Foo.f(2)
2
>>> Foo().f(2)
<__main__.Foo object at 0x7b16f5e810> 2

Is there any difference between f and print? Is this a bug?

Activity

  1. added
    docsDocumentation in the Doc dir
    pendingThe issue will be closed if no feedback is provided
    on Apr 9, 2025
  2. skirpichev commented on Apr 9, 2025

    @skirpichev
    Member

    Is there any difference between f and print?

    There is:

    >>> f = lambda *args: print(*args)
    >>> f.__self__
    Traceback (most recent call last):
      File "<python-input-1>", line 1, in <module>
        f.__self__
    AttributeError: 'function' object has no attribute '__self__'. Did you mean: '__call__'?
    >>> print.__self__
    <module 'builtins' (built-in)>

    If you take look on the print declaration, it has self argument (bound to it's module):

    cpython/Python/bltinmodule.c

    Lines 2159 to 2162 in 16dcb57

    static PyObject *
    builtin_print_impl(PyObject *module, PyObject * const *args,
    Py_ssize_t args_length, PyObject *sep, PyObject *end,
    PyObject *file, int flush)

    IIUIC, rules for module functions are like for classmethods, described here: https://docs.python.org/3/reference/datamodel.html#instance-methods

    Maybe it should be explained better in https://docs.python.org/3.14/reference/datamodel.html#built-in-functions. BTW, __self__ description here is wrong - at least here we have a documentation issue.

  3. self-assigned this
    on Apr 9, 2025
  4. removed
    pendingThe issue will be closed if no feedback is provided
    on Apr 9, 2025
  5. removed their assignment
    on Apr 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions