python / python/typeshed

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

Open
#15,007 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stubs: improvement
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with stdlib/builtins.pyi, especially the int.new and str.new definitions linked in the issue, and inspect the corresponding built-in constructor stubs for bool and bytes. Check how existing type checkers handle default parameters versus separate overloads, then ensure the stubs distinguish no-argument calls from calls with an argument and validate the resulting inferred constant values.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.