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

Overload hash generation functions to make return types more specific #2047

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

samueljsb
Copy link

@samueljsb samueljsb commented May 15, 2024

Before this change, the return type for these functions was always bytes| str. However, the type can be narrowed based on the value passed to raw_output.

This change adds overload annotations for the two allowable values to allow type checkers to narrow the type and correctly infer the exact return type.

Resolves #2046


As opposed to the example in the issue, this now shows the correct types:

$ cat t.py
import faker

fake = faker.Faker()

x = fake.md5(raw_output=False)
reveal_type(x)

y = fake.md5(raw_output=True)
reveal_type(y)

x = fake.sha1(raw_output=False)
reveal_type(x)

y = fake.sha1(raw_output=True)
reveal_type(y)

x = fake.sha256(raw_output=False)
reveal_type(x)

y = fake.sha256(raw_output=True)
reveal_type(y)

$ mypy t.py
t.py:6:13: note: Revealed type is "builtins.str"
t.py:9:13: note: Revealed type is "builtins.bytes"
t.py:12:13: note: Revealed type is "builtins.str"
t.py:15:13: note: Revealed type is "builtins.bytes"
t.py:18:13: note: Revealed type is "builtins.str"
t.py:21:13: note: Revealed type is "builtins.bytes"
Success: no issues found in 1 source file

@fcurella
Copy link
Collaborator

fcurella commented Aug 1, 2024

Hi! Could you push something to your branch, so that workflow can run again?

Before this change, the return type for these functions was always
`bytes| str`. However, the type can be narrowed based on the value
passed to `raw_output`.

This change adds overload annotations for the two allowable values to
allow type checkers to narrow the type and correctly infer the exact
return type.

Resolves joke2k#2046
@fcurella
Copy link
Collaborator

the stub file (faker/proxy.pyi) is meant to be autogenerated by generate_stubs.py, which currently does not recognize @overloaded signatures. Could you look into adding support for @overload to generate_stubs.py?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Type annotations on md5, sha1, and sha256 should be overloaded
2 participants