Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to disallow specific types for a TypeVar #599

Closed
Apo- opened this issue Dec 10, 2018 · 7 comments
Closed

Ability to disallow specific types for a TypeVar #599

Apo- opened this issue Dec 10, 2018 · 7 comments
Labels
resolution: duplicate The idea/problem was already reported topic: feature Discussions about new features for Python's type annotations

Comments

@Apo-
Copy link

Apo- commented Dec 10, 2018

Couldn't find any discussions on this, but it would be convenient to be able to specify some types to not be allowed for a TypeVar. For example to be able to say:

from typing import TypeVar


T = TypeVar('T', not_allowed=(int, float))


def foo(_: T): pass


foo(42)       # Error
foo(42.0)     # Error
foo('42')     # Ok

A motivating example is the following:

from typing import Union, Generic, TypeVar


T = TypeVar('T')


class Expected(Generic[T]):
    def __init__(self, value_or_error: Union[T, Exception]):
        self._value_or_error = value_or_error

    def is_valid(self) -> bool:
        return not isinstance(self._value_or_error, Exception)

where T shouldn't be an Exception.

SO post: https://stackoverflow.com/questions/53696345/disallow-specific-types-for-a-typevar-in-python

@JukkaL
Copy link
Contributor

JukkaL commented Dec 10, 2018

I don't think that there's a way to do this. I'll leave this issue open as a potential new feature, though it seems low priority unless perhaps we can find additional use cases.

@Apo-
Copy link
Author

Apo- commented Dec 11, 2018

Ok, thanks. If something like that does end up becoming a feature, let me know if there's anything I can do to help.

@guillaume-chevalier
Copy link

New use case: disallow nesting a type into itself for flat dicts.

from collections import OrderedDict
from typing import List, Tuple, Dict, Any, Union

NamedTupleList = List[Tuple[str, 'BaseStep']]

MaybeOrderedDict = Union[Dict, OrderedDict]
FlatHyperparams = MaybeOrderedDict[str, Any]  # Any except MaybeOrderedDict.
DictHyperparams = MaybeOrderedDict[str, Union[MaybeOrderedDict, Any]]

Here is an example of flat dict (FlatHyperparams):

    {
         "b.a.learning_rate": 7,
         "b.learning_rate": 9
     }

And a nested dict (DictHyperparams)

    {
         "b": {
             "a": {
                 "learning_rate": 7
             },
             "learning_rate": 9
         }
     }

Source code: https://github.com/Neuraxio/Neuraxle/blob/0.1/neuraxle/typing.py

@ilevkivskyi
Copy link
Member

#614 is also related. It seems to there was an issue for Not[SomeType], but can't find it now.

@Iftahh
Copy link

Iftahh commented Feb 13, 2020

Here is a use case I'm interested in (very similar to what is described in #614)

A function that wraps the argument in a list - unless the type is already a list

This is what I would like to have - except I can't communicate "anything else" to MyPy

ListOrTuple = TypeVar("ListOrTuple", List, Tuple)
AnythingElse = TypeVar("AnythingElse")

@overload
def as_list(val: ListOrTuple) -> ListOrTuple: ...

@overload
def as_list(val: AnythingElse) -> List[AnythingElse]: ...

def as_list(val):
    return val if isinstance(val, (list, tuple)) else [val]

@jbrockmendel
Copy link

It seems to there was an issue for Not[SomeType], but can't find it now.

#213 (comment)

@overload
def as_list(val: AnythingElse) -> List[AnythingElse]: ...

Same thing led me here. https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/lib.pyi#L37 is_float(obj) is effectively isinstance(obj, (float, np.floating) check, so its full behavior could be specified with two overloads with this feature. Then we wouldn't need ignores like https://github.com/pandas-dev/pandas/blob/master/pandas/core/dtypes/cast.py#L197

@srittau srittau added topic: feature Discussions about new features for Python's type annotations resolution: duplicate The idea/problem was already reported labels Nov 4, 2021
@srittau
Copy link
Collaborator

srittau commented Nov 4, 2021

Closing as a more specific variant of #801.

@srittau srittau closed this as completed Nov 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
resolution: duplicate The idea/problem was already reported topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

7 participants