Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line With Statement

#1
Python One Line With Statement



The with statement replaces former try...finally blocks in Python. It ensures that clean-up code is executed. For example, it closes open files before leaving the block. Consider this code example (assuming this code is stored in a file named 'code.py'):

with open('code.py') as code: print(code.read())

The output of this code would be the code itself (for nerds: a piece of code that generates itself is called a Quine):

''' OUTPUT
with open('code.py') as code: print(code.read()) '''

No matter what goes wrong inside the with block, Python will close the open file before moving on in the code. This way, you don’t need to enclose the code with a try...except statement.

Single Expression ‘With’ Statement in One Line


Python One Line With Statement

Problem: Can you write the with statement in a single line of code?

Solution: Yes, you can write the with statement in a single line of code if the loop body consists only of one statement:

with open('code.py') as code: print(code.read())

In general, you can write any indentation block (like if statements, with environments, or while loops) in a single line of code if the body consists of only one statement.

Exercise: The following interactive code throws an error if you run it. Fix the bug and run the correct code!

Multi Expression ‘With’ Statement in One Line


If the body consists of multiple statements, you can use a semicolon between the different statements:

with open('code.py') as code: print('The code:') print(code.read())

The previous code block becomes:

with open('code.py') as code: print('The code:'); print(code.read())

Note that in this particular instance, the semantics actually change because the code reads its own source file! But in all other cases, the semantics remain the same.

As soon as you have nested blocks like a for loop inside a with block, you cannot use this approach anymore because the code would become ambiguous. Believe it or not but the indentation serves a real purpose in Python! ?

Nested Indentation Blocks in a One-Line ‘With’ Statement


If you know the Finxter tutorials, you also know that I seldomly conclude with such a statement “XYZ is impossible” because in most cases, it isn’t. If you’re in doubt whether you can compress an algorithm into a single line of code—don’t. You can compress all algorithms into a single line!

In most cases, you can avoid nested blocks by using list comprehension (rather than a for loop) or the ternary operator (rather than an if block).

Consider the following example with a for loop inside a with block:

with open('code.py') as code: for i in range(10): print(code.read())

Problem: One-Linerize a nested with block!

Wrong Solution: Write it into a single line:

Syntax Error With Statement Single Line

Correct Solution: Replace the inner for loop with a list comprehension statement!

with open('code.py') as code: [print(code.read()) for i in range(10)]

While this code runs and solves the problem, please note that the chosen example does not make a lot of sense. The file is read only once—even if you place it into a for loop. The reason is that the file reader is done reading the file after the first iteration. In subsequent iterations it only reads the remaining characters (there aren’t any) so the output is not 10x only 1x the file contents.

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Python One-Liners Book


Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!



https://www.sickgaming.net/blog/2020/07/...statement/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Check Python Version from Command Line and in Script xSicKxBot 0 1,912 08-24-2023, 01:34 PM
Last Post: xSicKxBot
  [Tut] Python Async With Statement — Simplifying Asynchronous Code xSicKxBot 0 1,342 04-28-2023, 03:04 AM
Last Post: xSicKxBot
  [Tut] How to Delete a Line from a File in Python? xSicKxBot 0 1,218 09-24-2022, 10:31 AM
Last Post: xSicKxBot
  [Tut] A Simple Guide for Using Command Line Arguments in Python xSicKxBot 0 1,134 08-14-2022, 05:49 PM
Last Post: xSicKxBot
  [Tut] How to Skip a Line in Python using \n? xSicKxBot 0 1,181 07-05-2022, 03:53 PM
Last Post: xSicKxBot
  [Tut] Line Charts — Learning Line Charts with Streamlit xSicKxBot 0 1,356 04-29-2022, 10:52 PM
Last Post: xSicKxBot
  [Tut] How to Read a File Line-By-Line and Store Into a List? xSicKxBot 0 1,355 10-24-2020, 03:12 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 1,251 09-21-2020, 02:58 PM
Last Post: xSicKxBot
  [Tut] Python One Line Generator xSicKxBot 0 1,314 09-17-2020, 09:29 PM
Last Post: xSicKxBot
  [Tut] Replacements For Switch Statement In Python? xSicKxBot 0 1,170 09-13-2020, 01:31 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016