Rock Solid Python with Python Typing Transcripts
Chapter: Typing in Python
Lecture: Functions: void Functions
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Next up, let's look at functions in a way that maybe you haven't thought about before.
0:06
So we could say def sayHello, give it a name, which is a string and it will print out, ""Hello there, name? What goes here?
0:24
Well before we put any type there, let's go over here and use this.
0:28
say x. First we'll just say say hello Michael. That's cool. What about say hello Sam. And
0:40
let's capture the value here. See if that runs. What does this even do? Well, didn't
0:46
crash. That's positive. But what is x? We can ask for its type like this and we can
0:52
actually print its value like that. And it turns out to be a none type in none. That's
1:00
weird, isn't it? Because PyCharm is saying it doesn't return anything and surely enough
1:06
down here there is no return statement. It's not like we said return none, which would
1:14
make that error go away even though it's still returning none all the time. PyCharm's checker
1:21
or linter doesn't have a way to distinguish, we just use even the word return, we still get the same value of none.
1:30
So if you have what in some languages is called a void method, a method that doesn't or function
1:35
that doesn't return anything, you might expect there to be a void keyword or something like that in Python.
1:43
But Python functions, even if there's no return keyword used whatsoever, always, as we just
1:50
always always return none. So if we explicitly say that here, we're setting up the type to
1:57
be correctly so to be correct, but here PyCharm still says, even though you set the type,
2:05
it doesn't return anything, you shouldn't be doing this. Okay. But functions always
2:11
return something. And if if you don't return anything, they still by default return none.
2:17
And so the way to express that is not an optional string or an optional something, but just explicitly none is what's returned here.
2:26
I suppose you could do none type if you really wanted. You could make your PyCharm error go away because it's not testing for that, but it
2:35
says you're not actually returning that. None is what you want to put here.
2:38
Okay, so that's how you handle expressing what the return type is when there is no return