Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Improve duck type compatibility of int with float #100268

Closed
Labels
@JakubTesarek

Description

@JakubTesarek

Feature or enhancement

Function arguments and variables annotated withfloat should not allow value of typeint.

Pitch

PEP484 suggested thatwhen an argument is annotated as having type float, an argument of type int is acceptable;. This allows this kind of typing to be valid:

x: float = 2

Butint is not subtype offloat and doesn't provide the same interface. Float provides methods that are not available inint:

  • is_integer
  • fromhex
  • hex

This violates LSP and is problematic especially withis_integer:

defmethod_requiring_whole_number_float(number:float):ifnumber.is_integer():        ...

This method clearly states that it requiresfloat and as an author of such code, I would expect thatis_integer would be available if my typing is correct.

There are workarounds (if int(number) == number:) but they render theis_integer useless as it can never be safely used.

Just adding the missing methods toint (or removing the extra methods fromfloat) would not be valid solution as there are other problems stemming from the fact thatint is notfloat. Eg.:

defsplit_whole_and_decimal(number:float)->tuple[str,str]:returnstr(number).split('.')# it's reasonable to expect that the output contains a dot `.` as  `float` does but `int` doesn't

I'm proposing an errata to PEP484 that will removewhen an argument is annotated as having type float, an argument of type int is acceptable;.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp