Rock Solid Python with Python Typing Transcripts
Chapter: Typing in Python
Lecture: If You Don't Know the Type
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
So far, we've been really sure about what types we want to work with. But sometimes you want to just be able to say,
0:07
I don't know what this type is going to be. And that's okay. Python has worked that way for its entire life until 3.5.
0:17
And still, it's an optional add-on gradual type of thing, this typing, right? What if you don't know the type?
0:25
Maybe I have an unknown type of thing, and it could be A number, it could be a list, it could be anything.
0:32
How do we express that it could be a number here, but there's no guarantee it's going to be a number next time? We use typing.any.
0:43
We look at typing.any, it's a special type indicating an unconstrained type. It's compatible with everything.
0:51
Any assumed to have all the methods that you might want to call on it. It has all the values. Basically, you can do whatever you want with it.
0:58
So typing that any often you would just write it as any like this. Maybe I'll comment that one out because this one runs. We'll let you do anything.
1:09
So we can print out unknown just so we get rid of the warning if I make it something else. Now it's going to be 78 again but another time.
1:22
Now maybe it's the set 7 and 8 and 8 which is really just 7 and 8. All of these are completely fine. You see no errors, no warnings because we said,
1:33
hey, this type is unconstrained. Let it do whatever it wants. What do we get in terms of autocomplete? Well, if it can be anything and you intersect
1:43
all of those possible things, what do you get? You get basically nothing. So if it can be anything, you don't get much editor help.
1:52
And obviously you don't get type checking if it was never meant to be a set. Well, it can still be a set.
1:58
Here's how you express that a type can be anything with the typing.any type.