Skip to content

Callable[[Any], None]" has no attribute "__defaults__" #11896

Description

@jpy-git

Bug Report

mypy produces the false positive Callable[[Any], None]" has no attribute "__defaults__" when code uses the __defaults__ attribute of a function.

To Reproduce

Consider this code:

>>> def foo(a) -> None: pass
>>> print(foo.__defaults__)  # None if no default arguments.
None
>>> def bar(a="abc") -> None: pass
>>> print(bar.__defaults__)  # tuple of default arguments.
("abc",)

Run mypy on a script containing this code and get the false-positive:

test.py:2: error: "Callable[[Any], None]" has no attribute "__defaults__"
test.py:4: error: "Callable[[Any], None]" has no attribute "__defaults__"
Found 2 errors in 1 file (checked 1 source file)

Expected Behavior

No mypy errors since it's a valid attribute of a function.

Actual Behavior

mypy errors shown above.

Your Environment

  • Mypy version used: mypy 0.930
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: Python 3.9.9
  • Operating system and version: MacOS Big Sur

Activity

  1. AlexWaygood commented on Jan 3, 2022

    @AlexWaygood
    Member

    It looks to me like the issue is that the definition for the (fictional) function class in typeshed/stdlib/builtins.pyi has not got many of the attributes that the (non-fictional) FunctionType class in typeshed/stdlib/types.pyi has.

    You can get similar mypy errors for the following attributes, which are also defined on types.FunctionType, but not on builtins.function:

    • foo.__closure__
    • foo.__kwdefaults__
    • foo.__get__
  2. jpy-git commented on Jan 3, 2022

    @jpy-git
    Author

    @AlexWaygood Is there any reason we can't just have builtins.function be a type alias for types.FunctionType since they're the same?
    i.e. function = types.FunctionType

    If not then I'm happy to just copy the attributes over from FuntionType 😄

  3. AlexWaygood commented on Jan 3, 2022

    @AlexWaygood
    Member

    There have been previous attempts to delete builtins.function, which have (sadly) gone badly (see python/typeshed#5799), but I'm not aware of any previous attempts to simply have builtins.function be a type alias for types.FunctionType. Try it, see what happens! 😀

  4. jpy-git commented on Jan 4, 2022

    @jpy-git
    Author

    Closing as we've fixed this in typeshed 👍

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

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions