Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,51 @@ static_assert(is_disjoint_from(Callable[[], None], Literal[b""]))
static_assert(is_disjoint_from(Callable[[], None], Literal[1]))
static_assert(is_disjoint_from(Callable[[], None], Literal[True]))
```

A callable type is disjoint from nominal instance types where the classes are final and whose
`__call__` is not callable.

```py
from ty_extensions import CallableTypeOf, is_disjoint_from, static_assert
from typing_extensions import Any, Callable, final

@final
class C: ...

static_assert(is_disjoint_from(bool, Callable[..., Any]))
static_assert(is_disjoint_from(C, Callable[..., Any]))
static_assert(is_disjoint_from(bool | C, Callable[..., Any]))

static_assert(not is_disjoint_from(str, Callable[..., Any]))
static_assert(not is_disjoint_from(bool | str, Callable[..., Any]))

def bound_with_valid_type():
@final
class D:
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...

static_assert(not is_disjoint_from(D, Callable[..., Any]))

def possibly_unbound_with_valid_type(flag: bool):
@final
class E:
if flag:
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...

static_assert(not is_disjoint_from(E, Callable[..., Any]))

def bound_with_invalid_type():
@final
class F:
__call__: int = 1

static_assert(is_disjoint_from(F, Callable[..., Any]))

def possibly_unbound_with_invalid_type(flag: bool):
@final
class G:
if flag:
__call__: int = 1

static_assert(is_disjoint_from(G, Callable[..., Any]))
```
20 changes: 20 additions & 0 deletions crates/ty_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2164,6 +2164,26 @@ impl<'db> Type<'db> {
true
}

(
Type::Callable(_) | Type::DataclassDecorator(_) | Type::DataclassTransformer(_),
Type::NominalInstance(instance),
)
| (
Type::NominalInstance(instance),
Type::Callable(_) | Type::DataclassDecorator(_) | Type::DataclassTransformer(_),
) if instance.class.is_final(db) => {
let member = self.member_lookup_with_policy(
db,
Name::new_static("__call__"),
MemberLookupPolicy::NO_INSTANCE_FALLBACK,
);
match member.symbol {
// TODO: ideally this would check disjointness of the `__call__` signature and the callable signature
Symbol::Type(ty, _) => !ty.is_assignable_to(db, CallableType::unknown(db)),
Symbol::Unbound => true,
}
}

(
Type::Callable(_) | Type::DataclassDecorator(_) | Type::DataclassTransformer(_),
_,
Expand Down
Loading