typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Adding Overloads of stdlib Built-in Types __new__ with No Arguments

Open matthewyu0311 opened this issue 1 month ago • 2 comments

Calling int() and str() with no arguments returns 0 and "" respectively, likewise for bool() == False and bytes() == b"". But to actually call these constructors without arguments is very unusual and is likely a mistake on part of the user.

# a and b are two strings
x = int(a)
y = int()    # typo, should be int(b)

x / y    # ZeroDivisionError

It will be helpful for type stubs to denote that such no-argument calls return a constant value, and for IDEs to possibly notify of such use.

Currently the stub for int.__new__ looks like this:

https://github.com/python/typeshed/blob/904ea9ec022ae75d282f6a4c34563e4e9b8eed15/stdlib/builtins.pyi#L257

class int:
    @overload
    def __new__(cls, x: ConvertibleToInt = 0, /) -> Self: ...

and str.__new__:

class str(Sequence[str]):
    @overload
    def __new__(cls, object: object = "") -> Self: ...

I suggest adding an overload with no argument and removing the default parameter value from the one-arg __new__, though I'm not sure if there are existing special behaviors of type checkers regarding builtins that I'm unaware of.

matthewyu0311 avatar Nov 09 '25 22:11 matthewyu0311

This makes sense to me. At least an exploratory PR would be welcome.

srittau avatar Nov 10 '25 16:11 srittau

previously discussed in https://github.com/python/typeshed/issues/6069 (the title mentions bool but the discussion covered other builtin types too). The exploratory PR is at https://github.com/python/typeshed/pull/10465

AlexWaygood avatar Nov 10 '25 16:11 AlexWaygood