Today we have another attempt to cram the uncrammable into a single line, found somewhere on the internet. Looking at this, linters don't just complain—they uninstall themselves from your device.
with open("t") as f:print(sum([sum([float(m) for m in "".join(filter(lambda x:x.isnumeric() or x.isspace() or x==".",l)).split()]) for l in f.readlines()]))🧐 What's happening here?
The author of this "masterpiece" set themselves a task: extract all numbers from a text file and sum them.
Why does this cause physical pain?
1️⃣ Memory isn't infinite.
f.readlines() dumps the entire file into RAM. If the file is 10 GB, your server will say "bye" faster than you finish reading this post.2️⃣ Character-by-character filtering via lambda. Gluing a string one character at a time with
"".join(filter(...)) is the slowest way to process strings in Python. Are we programming or sorting beads?3️⃣ Nested list comprehensions. Readability is on par with Egyptian hieroglyphs. To figure out where a bracket closes, you need to call an exorcist.
4️⃣ PEP8 has left the chat. No spaces after
: and around operators isn't saving space; it's disrespecting others.Conclusion: We got code that runs slowly, eats memory, and is completely unreadable.
✅ How to do it properly?
If you need to extract numbers from text, there are regular expressions.
Here's how this code should look in a sane world:
import re
def total_sum_from_file(file_path: str) -> float:
total = 0.0
# Use context manager and line iterator
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
# Find everything that looks like a number (integer or decimal)
numbers = re.findall(r"[-+]?\d*\.\d+|\d+", line)
total += sum(map(float, numbers))
return total
print(total_sum_from_file("t.txt"))Why this is better:
1. Readability: Even a junior can understand what's happening in 5 seconds.
2. Memory: We read the file line by line. If the file is 10 GB, this code won't crash.
3. Speed:
re.findall at the C level runs faster than your character-by-character filter in Python.#code_smoker
Comments
0No comments yet.