I have seen some code in Pinax and other django apps that instead of pass, an empty return statement is used. What is the difference and would it have any effect on, for example, the django code below that I am running? The code is a signal method that automatically saves the hashtags into taggit Tag objects for a tweet object.
I saw a question here about whether having or not having a return statement in PHP makes a difference in the interpreted bytecode, but I am not sure if it is relevant to Python.
import re TAG_REGEX = re.compile(r'#(?P<tag>\w+)') def get_tagged(sender, instance, **kwargs): """ Automatically add tags to a tweet object. """ if not instance: return # will pass be better or worse here? post = instance tags_list = [smart_unicode(t).lower() for t in list(set(TAG_REGEX.findall(post.content)))] if tags_list: post.tags.add(*tags_list) post.save() else: return # will a pass be better or worse here? post_save.connect(get_tagged, sender=Tweet)
Summary: return None is (or can imagined to be) always implicitly added below the last line of every function definition. It can also only appear in functions and immediately exits them, returning a value (or None as default). pass has no semantic meaning, it does not get interpreted in any way.
In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
Difference between pass and continuecontinue forces the loop to start at the next iteration whereas pass means "there is no code to execute here" and will continue through the remainder of the loop body.
In Python, the pass keyword is an entire statement in itself. This statement doesn't do anything: it's discarded during the byte-compile phase.
if not instance: return # will pass be better or worse here?
Worse. It changes the logic. pass
actually means: Do nothing. If you would replace return
with pass
here, the control flow would continue, changing the semantic of the code.
The purpose for pass
is to create empty blocks, which is not possible otherwise with Python's indentation scheme. For example, an empty function in C looks like this:
void foo() { }
In Python, this would be a syntax error:
def foo():
This is where pass
comes handy:
def foo(): pass
This illustrates some earlier answers.
def p(): "Executes both blocks." if True: print(1) pass if True: print(2) pass def r(): "Executes only the first block." if True: print(1) return if True: print(2) return
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