In Python, the Show
Sometimes In this tutorial, you’ll learn:
Python pass Statement: Syntax and SemanticsIn Python syntax, new indented blocks follow a colon character ( >>>
After the In this case, there are two statements in the body that are repeated for each value:
The statements inside this type of block are technically called a suite in the Python grammar. A suite must include one or more statements. It can’t be empty. To do nothing inside a suite, you can use Python’s special >>>
In this In some cases, explicitly telling Python to do nothing serves an important purpose. For example, because the >>>
Even
if you don’t want to add any code inside the To fix this, you can use >>>
Now, thanks to Temporary Uses of passThere are many situations in which It might sound strange to write code that will be deleted later, but doing things this way can accelerate your initial development. Future CodeThere are many cases where the structure of the code requires, or could use, a block. While you may eventually have to write code there, it’s sometimes hard to get out of the flow of working on something specific and start working on a dependency. In these cases, a As a concrete example, imagine writing a function that processes a string and then both writes the result to a file and returns it:
This function saves and returns the middle third of a string.
You don’t need to finish implementing It’s possible to comment out the call to
This
function doesn’t do anything, but it allows you to test Another use case for
This structure identifies what should be printed in each case, which gives you the skeleton of the solution. Such structural skeletons are useful when trying to figure out the branching logic of which For example, in this case, a critical insight is that the first After you figure out the core logic of the problem, you can decide whether you’ll
This function is straightforward to use since it directly prints the strings. However, it’s not a pleasant function to test. This can be a useful trade-off. However, in coding interviews, the interviewer will sometimes ask you to write tests. Writing the structure first allows you to make sure you understand the logical flow before checking what the other requirements are. An alternative would be to write a function that returns the string and then do the looping elsewhere:
This function pushes the printing functionality up the stack and is easier to test. Figuring out the core conditionals and structure of the problem using
This approach is also useful when writing classes. If you need to write a class to implement something, but you don’t fully understand the problem domain, then you can use For example, imagine you’re implementing
a This allows you to instantiate members of the class and pass them around without having to decide what properties are relevant to the class. Markers for DebuggersWhen you run code in a debugger, it’s possible to set a breakpoint in the code where the debugger will stop and allow you to inspect the program state before continuing. When a test run triggers a breakpoint often, such as in a loop, there might be many instances where the
program state isn’t interesting. To address this problem, many debuggers also allow a conditional breakpoint, a breakpoint that will trigger only when a condition is true. For example, you might set a breakpoint in a However, many debuggers allow you to set only a few basic conditions on your breakpoints, such as equality or maybe a size comparison. You might need a more complicated condition, such as checking that a string is a palindrome before breaking. While the debugger might not be capable of checking for palindromes, Python can do so with minimal effort. You can take advantage of that functionality by having a do-nothing
By checking for palindromes with Although the Empty FunctionsIn some cases, it may even be useful for you to include an empty function in the deployed version of your code. For example, a function in a library might expect a callback function to be passed in. An even more common case is when your code defines a class that inherits from a class that expects a method to be overridden. However, in your specific case, you don’t need to do anything. Or perhaps the reason you’re overriding the code is to prevent an overridable method from doing anything. In all those cases, you’ll need to write an empty function or method. Once again, the problem is that having no lines after the >>>
This fails because a function, like other blocks, has to include at least one statement. To fix this problem, you can use >>>
Now that the function has a statement, even one that does nothing, it’s valid Python syntax. As another example, imagine you have a function that expects a file-like object to write to. However, you want to call the function for another reason and would like to discard the output. You can use
Instances of this class support the In both of these examples, it’s important that a method or function exists, but it doesn’t need to do anything. Because Python blocks must have statements, you can make empty functions or methods valid by using Empty ClassesIn Python, exception inheritance is important because it marks which exceptions are caught. For example, the built-in exception >>>
The exception Sometimes you want to raise specific exceptions in your code because they have a specific recovery path. However, you want to make sure that those exceptions inherit from a general exception in case someone is catching the general exception. These exception classes have no behavior or data. They’re just markers. In order to see the usefulness of a rich exception hierarchy, you can consider password rule checking. Before trying to change the password on a website, you want to test it locally for the rules it enforces:
Each of those errors should have its own exception. The following code implements those rules:
This function will raise an exception if the password doesn’t follow the specified rules. A more realistic example would note all the rules that haven’t been followed, but that’s beyond the scope of this tutorial. You can use this function in a wrapper to print the exception in a nice way: >>>
In this case, In some situations, your users might not care exactly which problems exist in the input. In that case, you would just want to catch
In this code, all invalid input is treated the same since you don’t care what problems the credentials have. Because of these differing use cases,
Each of these exceptions describes a different rule being violated. In code that matches a string against more sophisticated rules, there might be many more of these, arranged in a complex structure. Despite the
need for four different classes, none of the classes has any behavior. The Marker MethodsSome methods in classes exist not to be called but to mark the class as somehow being associated with this method. The Python standard library has the
If you’re writing code to analyze usage patterns of a web server, then you might want to differentiate between requests coming from logged-in users and those coming from unauthenticated connections. You
could model this by having an Nothing should ever instantiate the
While a real Because >>>
Classes with Because method bodies can’t be empty, you have to put
something in A more modern way to indicate methods are needed is to use a A The methods in a >>>
Demonstrating how to use a There are more examples of such markers being used outside the Python language and standard libraries. For example, they’re used in the
In all these cases, classes need to have methods but never call them. Because of this, the body doesn’t matter. But since the body can’t be empty, you can use the Alternatives to passThe Any expression in Python is a valid statement, and every constant is a valid expression. So the following expressions all do nothing:
You can use any one of these expressions as the only statement in a suite, and it will accomplish the same task as
In general, the DocstringsThere’s one important exception to the idiom of using The Even when a docstring isn’t mandatory, it’s often a good substitute for the
In all these cases, the docstring makes the code clearer. The docstring will also be visible when you use this code in the interactive interpreter and in IDEs, making it even more valuable. One technical advantage of docstrings, especially for those functions or methods that never execute, is that they’re not marked as “uncovered” by test coverage checkers. EllipsisIn mypy stub files, the recommended way to fill a block is to use an ellipsis ( >>>
The The original use for
This function not only does nothing, but it’s also in a file that the Python interpreter never evaluates. Raise an ErrorIn cases where the functions or methods are empty because they never execute, sometimes the best body for them is Permanent Uses of passSometimes the use of the Using pass in Exception CatchingWhen using If you want to make sure a file doesn’t exist, then you can use Here’s a function that removes a file and doesn’t fail if the file doesn’t exist:
Because nothing needs to be done if a Note that the In this case, you could also use the context manager For example, if
you wanted to have
Here, you ignore the In this example, the order of the Using pass in if … elif ChainsWhen you use long Imagine that a recruiter gets tired of using the fizz-buzz challenge as an interview question and decides to ask it with a twist. This time, the rules are a bit different:
The interviewer believes that this new twist will make answers more interesting. As with all coding interview questions, there are many ways to solve this challenge. But one way is to use a
The In this example, if
you removed the This use case for the ConclusionYou now understand what the Python In this tutorial, you’ve learned:
Now you’ll be able to write better and more efficient code by knowing how to tell Python to do nothing. What is the use of empty loop in Python?It can be used when a statement is required syntactically but the program requires no action.
What does it mean empty loop?Loved by our community
An empty loop is a loop which does not have any updation or value of iteration. For example, for(int i = 1;;) (in Java) An empty loop is infinite.
How do you write an empty loop in Python?In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement. We can use pass in empty while statement also.
Why do we use empty loop?For creating a loop that runs infinitely, we can use empty statements. However, if we use break statements inside the body of the loop, then the loop can terminate. If we want to create a for-loop or while loop that has an empty body, we can use an empty statement.
|