Comments (5)
Workaround is to change else:
-> elif type(val) is Duration:
but this should be unnecessary.
from mypy.
Using isinstance
instead of a type
check doesn't report an issue but in this case where int
is a parent class of Duration
that test is incorrect.
def output(val: Duration | int) -> None:
if isinstance(val, int): # Invalid due to Duration being a sub class of int
print(f"type: {type(val)} = int: {val}")
else:
print(f"type: {type(val)} = duration: {val.nanoseconds()}") # Never called
from mypy.
Mypy's behavior is correct here. The type cannot be safely narrowed to just Duration
in the "else" case. It's possible for other subtypes of int
to be passed to the function, and they would not pass the test type(val) is int
.
class OtherIntSubclass(int):
pass
output(OtherIntSubclass(1))
You've already identified the correct way to fix this bug in your code — by using isinstance
.
from mypy.
Thanks for clarification, coming from other languages my expectation was for exact type matching requirement from hint and hence Duration | int
meant only Duration
or int
exactly, so OtherIntSubclass
was not valid.
I believe what you're saying is this is not the case and instead Duration
or int
means those classes or any subclasses, is that correct @erictraut?
from mypy.
Answering my own question from PEP 484
Expressions whose type is a subtype of a specific argument type are also accepted for that argument.
Capturing for others the fix for this case is to invert the test an look for the more specific type, which is easy in this case given one is base type, not so easy for other types as you need know the types of the entire chain.
def output(val: Duration | int) -> None:
if isinstance(val, Duration):
print(f"type: {type(val)} = duration: {val.nanoseconds()}")
else:
print(f"type: {type(val)} = int: {val}")
Thanks for the quick response, closing as it is working as intended.
from mypy.
Related Issues (20)
- overloaded class-decorator is seen as not Callable when used on an overloaded method HOT 2
- 1.9.0 Release Tracking Issue HOT 10
- mypyc: `KeyError 'expr'` with NamedTuple HOT 1
- Optional[TypeVar] does not preserve type of TypeVar when given Union type HOT 1
- Overloaded function signature will never be matched
- false positive on interaction between `@property`, `@lru_cache`, and inheritance HOT 2
- False negative with property and decorator
- Crash Report: Internal Error for typechecking openai with pydantic-plugin HOT 5
- The attrs.field converter parameter does not support higher-order functions.
- Descriptors misbehave with `NoReturn`/`Never`, with `@overload`s, etc. HOT 4
- Stubgen crashes on TypeVarTuple usage
- If plugin has same name as top-level module which has been imported before mypy runs (e.g., you are using api), mypy picks up the wrong file HOT 1
- str counts as a Callable[..., str], but not as a Callable[..., TypeVar] HOT 1
- `Callable` not deduced correctly
- False positive typing.Self has incompatible type when method uses class' generic type HOT 3
- Calls to `.get` on TypeVars bound to TypedDict narrow to `object` HOT 2
- Presence of property in Protocol causes false positive in multiple inheritance scenario HOT 1
- Generate an error if using a type from the numbers module HOT 1
- Using numpy types conditionally gives confusing `[assignment]` error HOT 2
- false "Attempted to reuse member name in Enum definition"
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mypy.