Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint as logical-and of multiple types

I know that Union allows you to specify the logical-or of multiple types. I'm wondering if there is a way to do something analogous for the logical-and, something like:

def foo(x: And[Bar, Baz]):

I know that one option is to just explicitly define a new type that inherits from both Bar and Baz, like this:

class BarAndBaz(Bar, Baz):
    ...

def foo(x: BarAndBaz):

In my context that option is not ideal.

like image 642
dshin Avatar asked Apr 17 '17 14:04

dshin


1 Answers

Based on helpful comments from @deceze and @JimFasarakisHilliard:

For all intents and purposes, you can use Union as if it were And, since a good IDE should auto-complete for types Bar and Baz if you declare a variable to be of type Union[Bar, Baz].

Something like this will also help with readability:

# IDE should treat And/Union equivalently; use And[T, U] to communicate
# that a variable is expected to be an instance of T *and* U, and
# Union[T, U] to communicate that it is expected to be an instance of T
# *or* U.
And = Union  

In my particular case, my IDE (PyCharm) was not behaving properly because it needed an update and a restart.

like image 167
dshin Avatar answered Oct 13 '22 01:10

dshin