Skip to content

Commit

Permalink
Add a FlexibleAlias to mypy_extensions (#5436)
Browse files Browse the repository at this point in the history
Currently there is no way to define generic type aliases that do not
depend on their type arguments or that are just directly a type
variable.

`FlexibleAlias[T, typ]` creates a type that depends on `T` but that is
expanded to `typ` during type alias expansion.

One target use case for this is in creating conditionally defined type
aliases that depend on their argument under certain configurations but
not under others, for example:
```
if BOGUS:
    Bogus = FlexibleAlias[T, Any]
else:
    Bogus = FlexibleAlias[T, T]
```
  • Loading branch information
msullivan authored Aug 9, 2018
1 parent 94dc83f commit 0d35e07
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions mypy_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,23 @@ class NoReturn: pass

def trait(cls):
return cls


# TODO: We may want to try to properly apply this to any type
# variables left over...
class _FlexibleAliasClsApplied:
def __init__(self, val):
self.val = val

def __getitem__(self, args):
return self.val


class _FlexibleAliasCls:
def __getitem__(self, args):
return _FlexibleAliasClsApplied(args[-1])


FlexibleAlias = _FlexibleAliasCls()

Id = _FlexibleAliasCls()

0 comments on commit 0d35e07

Please sign in to comment.