Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inherit type from functions default value #9545

Closed
dpinol opened this issue Oct 7, 2020 · 2 comments
Closed

Inherit type from functions default value #9545

dpinol opened this issue Oct 7, 2020 · 2 comments

Comments

@dpinol
Copy link

dpinol commented Oct 7, 2020

Feature
I would expect that default valued argument inherit the value type. Hence the following code would fail because "f" is called with a str instead of an int, and because it internally assigns to an str.
Personally I would implement this by default, but having a flag to enable it could also be an option.

def f(a=5) -> None:
    a="ads"

def g() -> None:
    f("asd")

Pitch
My rationale for adding the check:

  1. That's the way it works in other languages (eg. typescript)
  2. default values are typically literals (since mutable objects are not good defaults), and it's rare that providing eg. an int default, an str would be also accepted. So, the most common case will require shorter code.
  3. If the developer wants to set a default value but wants to allow other types, it feels more natural to have to explicitly add ": Any"
  4. Mypy already reports "Incompatible types in assignment" for the code below, which is quite conceptually similar.
class A:
    a=5

A.a = "asd"
  1. Tools like pycharm automatically inherit the type from the default value. See snapshot
    image

thanks!

@dpinol dpinol added the feature label Oct 7, 2020
@dpinol dpinol changed the title Functions Default value Inherit type from functions default value Oct 7, 2020
@gvanrossum
Copy link
Member

Arguably this should be discussed on typing-sig first.

@hauntsaninja
Copy link
Collaborator

Basically a duplicate of #10149

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Apr 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants