Skip to content

Commit f379eb6

Browse files
authored
[ty] Treat lambda functions as instances of types.FunctionType (#18431)
1 parent 4769888 commit f379eb6

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

crates/ty_python_semantic/resources/mdtest/expression/lambda.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,22 @@ a5: Callable[[], None] = lambda x: None
115115
# error: [invalid-assignment]
116116
a6: Callable[[int], None] = lambda: None
117117
```
118+
119+
## Function-like behavior of lambdas
120+
121+
All `lambda` functions are instances of `types.FunctionType` and should have access to the same set
122+
of attributes.
123+
124+
```py
125+
x = lambda y: y
126+
127+
reveal_type(x.__code__) # revealed: CodeType
128+
reveal_type(x.__name__) # revealed: str
129+
reveal_type(x.__defaults__) # revealed: tuple[Any, ...] | None
130+
reveal_type(x.__annotations__) # revealed: dict[str, @Todo(Support for `typing.TypeAlias`)]
131+
reveal_type(x.__dict__) # revealed: dict[str, Any]
132+
reveal_type(x.__doc__) # revealed: str | None
133+
reveal_type(x.__kwdefaults__) # revealed: dict[str, Any] | None
134+
reveal_type(x.__module__) # revealed: str
135+
reveal_type(x.__qualname__) # revealed: str
136+
```

crates/ty_python_semantic/src/types/infer.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4956,7 +4956,7 @@ impl<'db> TypeInferenceBuilder<'db> {
49564956
// TODO: Useful inference of a lambda's return type will require a different approach,
49574957
// which does the inference of the body expression based on arguments at each call site,
49584958
// rather than eagerly computing a return type without knowing the argument types.
4959-
CallableType::single(self.db(), Signature::new(parameters, Some(Type::unknown())))
4959+
CallableType::function_like(self.db(), Signature::new(parameters, Some(Type::unknown())))
49604960
}
49614961

49624962
/// Returns the type of the first parameter if the given scope is function-like (i.e. function or lambda).

0 commit comments

Comments
 (0)