Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Pass and None in Python

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!

like image 616
GSAT Avatar asked Dec 26 '17 01:12

GSAT


People also ask

What is a pass in Python?

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.

What is the difference between pass and return in Python?

Return exits the current function or method. Pass is a null operation and allows execution to continue at the next statement.

What is the difference between None and None in Python?

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.

How do you pass None value in Python?

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.


2 Answers

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).

like image 72
poke Avatar answered Oct 28 '22 09:10

poke


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.

like image 30
pushkin Avatar answered Oct 28 '22 08:10

pushkin