faker icon indicating copy to clipboard operation
faker copied to clipboard

Overload hash generation functions to make return types more specific

Open samueljsb opened this issue 1 year ago • 1 comments

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

samueljsb avatar May 15 '24 15:05 samueljsb

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

fcurella avatar Aug 01 '24 16:08 fcurella

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?

fcurella avatar Oct 21 '24 13:10 fcurella