I would personally like to know the semantic difference between using Pass and None. I could not able to find any difference in execution.
PS: I could not able to find any similar questions in SO. If you find one, please point it out.
Thanks!
Python pass Statement The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
Return exits the current function or method. Pass is a null operation and allows execution to continue at the next statement.
None vs NoneType in Python In other words, the difference between None and NoneType in Python is that: None is a Python object. NoneType is a class that implements the None object.
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
pass
is a statement. As such it can be used everywhere a statement can be used to do nothing.
None
is an atom and as such an expression in its simplest form. It is also a keyword and a constant value for “nothing” (the only instance of the NoneType
). Since it is an expression, it is valid in every place an expression is expected.
Usually, pass
is used to signify an empty function body as in the following example:
def foo():
pass
This function does nothing since its only statement is the no-operation statement pass
.
Since an expression is also a valid function body, you could also write this using None
:
def foo():
None
While the function will behave identically, it is a bit different since the expression (while constant) will still be evaluated (although immediately discarded).
In simple terms, None
is a value that you can assign to a variable that signifies emptiness. It can be useful as a default state:
a = None
def f():
a = 5
f()
pass
is a statement that is like a nop. It can be useful when you are defining function stubs, for instance:
def f():
pass
In C-like languages, you would be able to define empty functions by simply putting nothing between the braces void f() { }
, but since Python uses indentation instead of braces to define blocks, you must put something in the body, and pass
is the idiomatic thing to put there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With