{"id":4891,"date":"2026-09-26T23:59:11","date_gmt":"2026-09-26T18:29:11","guid":{"rendered":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/"},"modified":"2026-09-26T23:59:11","modified_gmt":"2026-09-26T18:29:11","slug":"mastering-python-code-tips-tricks-and-best-practices","status":"publish","type":"post","link":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/","title":{"rendered":"Mastering Python Code: Tips, Tricks, and Best Practices"},"content":{"rendered":"<p>text<br \/>\nTraceback (most recent call last):<br \/>\n  File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 442, in <module><br \/>\n    main()<br \/>\n  File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in main<br \/>\n    results = [process_record(r) for r in large_dataset_query]<br \/>\n  File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in <listcomp>\n    results = [process_record(r) for r in large_dataset_query]<br \/>\n  File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 89, in process_record<br \/>\n    buffer.append(deep_copy_transform(r))<br \/>\nMemoryError<br \/>\n[ 172834.123456] Out of memory: Kill process 12834 (python3.11) score 942 or sacrifice child<br \/>\n[ 172834.123489] Killed process 12834 (python3.11) total-vm:64213424kB, anon-rss:60123412kB, file-rss:0kB, shmem-rss:0kB<br \/>\n[ 172834.123510] oom_reaper: reaped process 12834 (python3.11), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB<\/p>\n<pre class=\"codehilite\"><code>I\u2019ve been staring at this screen for forty-eight hours. My eyes feel like they\u2019ve been scrubbed with industrial-grade sandpaper. The fluorescent lights in this data center annex are humming at a frequency that is currently vibrating my last remaining nerve. All of this\u2014the downtime, the lost revenue, the frantic Slack pings from &quot;Stakeholders&quot;\u2014because a junior developer decided that their **python code** was too &quot;elegant&quot; to follow basic memory management principles. \n\nThey wanted &quot;readability.&quot; They wanted &quot;idiomatic&quot; structures. What they got was a 64GB heap exhaustion that triggered a cascading failure across the entire analytics cluster. When the OOM killer starts hunting your processes like a wolf in a sheep pen, you don't talk about &quot;clean code.&quot; You talk about survival.\n\n## INCIDENT #4092-B: THE OOM KILLER\u2019S MIDNIGHT SNACK\n\nThe call came in at 3:14 AM on a Sunday. The primary ingestion node for our telemetry pipeline went dark. By 3:20 AM, the failover nodes followed suit. This wasn't a network partition. This wasn't a hardware failure. This was a slow, agonizing death by a thousand allocations. \n\nI pulled the logs and saw the `MemoryError` screaming from the stderr of our main processing service. We\u2019re running Python 3.11.5. It\u2019s supposed to be faster, right? The &quot;Specialized Adaptive Interpreter&quot; is supposed to optimize our bytecode. But no amount of interpreter magic can save you from **python code** that treats RAM like an infinite resource. \n\nThe culprit was a single script designed to &quot;summarize&quot; user activity logs. The junior dev\u2014let\u2019s call him Kevin, because it\u2019s always a Kevin\u2014decided that instead of streaming the data from our PostgreSQL instance (running SQLAlchemy 2.0.21, by the way), he would just load the entire result set into a list comprehension. \n\n```bash\n# ps aux output during the spike\nUSER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND\nroot     12834 98.2 94.1 64213424 60123412 ?   Rs   03:00  12:45 python3.11 processor.py\n<\/code><\/pre>\n<p>Look at that RSS. 60GB. On a machine with 64GB of physical RAM. The kernel was gasping for air. I ran <code>strace -p 12834<\/code> and watched a literal wall of <code>brk()<\/code> and <code>mmap()<\/code> calls. The <strong>python code<\/strong> was begging the kernel for more pages, and the kernel, in its infinite mercy, finally decided to put the process out of its misery.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6ab96f929b348\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6ab96f929b348\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#TICKET_991_THE_%E2%80%9CELEGANT%E2%80%9D_GENERATOR_THAT_WASNT\" >TICKET #991: THE &#8220;ELEGANT&#8221; GENERATOR THAT WASN&#8217;T<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#DEBUG_LOG_THE_DICTIONARY_LOOKUP_DEATH_SPIRAL\" >DEBUG LOG: THE DICTIONARY LOOKUP DEATH SPIRAL<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#ANALYSIS_THE_GIL_AS_A_CHOKEPOINT_FOR_CONCURRENCY\" >ANALYSIS: THE GIL AS A CHOKEPOINT FOR CONCURRENCY<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#DATABASE_TRACE_SQLALCHEMY_2021_AND_THE_N1_APOCALYPSE\" >DATABASE TRACE: SQLALCHEMY 2.0.21 AND THE N+1 APOCALYPSE<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#RESOLUTION_STRIPPING_THE_ABSTRACTIONS_TO_THE_BONE\" >RESOLUTION: STRIPPING THE ABSTRACTIONS TO THE BONE<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#THE_AFTERMATH_LESSONS_IN_STABILITY\" >THE AFTERMATH: LESSONS IN STABILITY<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#Related_Articles\" >Related Articles<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"TICKET_991_THE_%E2%80%9CELEGANT%E2%80%9D_GENERATOR_THAT_WASNT\"><\/span>TICKET #991: THE &#8220;ELEGANT&#8221; GENERATOR THAT WASN&#8217;T<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Kevin thought he was being smart. He used a generator expression at first, but then he realized he needed to &#8220;sort the results for the UI.&#8221; So, he cast the whole thing to a list. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\"># The offending python code snippet\ndef get_data():\n    query = session.query(ActivityLog).filter(ActivityLog.timestamp &gt; last_week)\n    return [r for r in query] # Kevin's &quot;fix&quot; for sorting later\n<\/code><\/pre>\n<p>In Python 3.11.5, every object has overhead. A simple integer isn&#8217;t just 4 or 8 bytes like in C. It\u2019s a <code>PyObject<\/code> structure. It\u2019s 28 bytes. Now multiply that by the 150 million rows Kevin was trying to pull into memory. Then add the overhead of the list itself, which needs to over-allocate to maintain O(1) append time. Then add the SQLAlchemy model overhead, where each instance tracks its own state, its own identity map, and its own internal dictionary.<\/p>\n<p>The <strong>python code<\/strong> was effectively creating a massive directed acyclic graph of objects that the Garbage Collector (GC) couldn&#8217;t even begin to reason about. I looked at the <code>gc.get_stats()<\/code> output before the crash. Generation 0 was firing every few milliseconds. Generation 2\u2014the place where objects go to die\u2014was ballooning. <\/p>\n<p>The problem with <strong>python code<\/strong> in a high-throughput environment is that the GC is a stop-the-world event. When you have 60GB of objects, the GC has to traverse those object references to see what can be deleted. It\u2019s walking a minefield. Every time the GC ran, the process would freeze for seconds, causing our heartbeat checks to fail, which caused Kubernetes to think the pod was dead, which caused a restart loop. A &#8220;death spiral&#8221; in the most literal sense.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"DEBUG_LOG_THE_DICTIONARY_LOOKUP_DEATH_SPIRAL\"><\/span>DEBUG LOG: THE DICTIONARY LOOKUP DEATH SPIRAL<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>I spent the next six hours digging into why the memory wasn&#8217;t being reclaimed even when we limited the batch size. It turns out Kevin\u2019s <strong>python code<\/strong> was using a dictionary to &#8220;cache&#8221; lookups for user metadata. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\"># More &quot;clever&quot; python code\nuser_cache = {u.id: u for u in session.query(User).all()}\n<\/code><\/pre>\n<p>In Python, dictionaries are hash tables. They are fast, sure. But they are also memory-hungry. Even with the PEP 468 optimizations that made dicts more compact, you\u2019re still looking at a significant footprint. Kevin had 5 million users in that cache. <\/p>\n<p>I ran a quick script to check the size: <code>sys.getsizeof(user_cache)<\/code>. It was massive. But the real killer wasn&#8217;t the dict itself; it was the fragmentation. Python\u2019s memory allocator (obmalloc) handles small objects (less than 512 bytes) by grouping them into &#8220;arenas&#8221; of 256KB. When Kevin\u2019s <strong>python code<\/strong> deleted an object, the memory wasn&#8217;t necessarily returned to the OS. If one tiny object in that 256KB arena was still &#8220;alive&#8221; (perhaps referenced by a stray pointer in a traceback or a global variable), the entire arena stayed resident in RAM.<\/p>\n<p>I had to use <code>tracemalloc<\/code> to find the leak. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\">import tracemalloc\ntracemalloc.start()\n# ... run Kevin's garbage ...\nsnapshot = tracemalloc.take_snapshot()\ntop_stats = snapshot.statistics('lineno')\nfor stat in top_stats[:10]:\n    print(stat)\n<\/code><\/pre>\n<p>The output confirmed my fears. The SQLAlchemy identity map was holding onto every single <code>ActivityLog<\/code> object ever instantiated. Kevin hadn&#8217;t used <code>session.expunge_all()<\/code> or <code>session.close()<\/code>. He just kept piling more data into the same session. The <strong>python code<\/strong> was essentially a memory leak by design.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"ANALYSIS_THE_GIL_AS_A_CHOKEPOINT_FOR_CONCURRENCY\"><\/span>ANALYSIS: THE GIL AS A CHOKEPOINT FOR CONCURRENCY<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Once I patched the memory leak by forcing <code>yield_per(1000)<\/code> on the SQLAlchemy queries and manually clearing the session, I hit the next wall: the Global Interpreter Lock (GIL). <\/p>\n<p>Kevin\u2019s <strong>python code<\/strong> was trying to be &#8220;performant&#8221; by using <code>threading.Thread<\/code> to process the logs in parallel. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\">threads = []\nfor i in range(cpu_count()):\n    t = threading.Thread(target=process_logs, args=(chunks[i],))\n    threads.append(t)\n    t.start()\n<\/code><\/pre>\n<p>I wanted to scream. This is a CPU-bound task. In Python, due to the GIL, only one thread can execute bytecode at a time. By spawning ten threads, Kevin wasn&#8217;t making the <strong>python code<\/strong> faster; he was making it slower. The overhead of context switching between threads, combined with the contention for the GIL, was driving the CPU load to 100% while the actual throughput dropped by 40%.<\/p>\n<p>I watched the <code>mpstat<\/code> output. One core was pinned at 100%, while the others were sitting at 10-15%, mostly handling kernel interrupts and I\/O wait. The <strong>python code<\/strong> was effectively serialized, but with the added penalty of thread management. <\/p>\n<p>I checked the <code>strace<\/code> again. I saw a constant stream of <code>futex(..., FUTEX_WAIT_BITSET_PRIVATE, ...)<\/code> calls. That\u2019s the sound of threads begging for the GIL. It\u2019s the sound of a system dying. Python 3.11.5 has some improvements in how it handles internal locks, but it can&#8217;t bypass the fundamental law of the GIL: one thread to rule them all, and in the darkness, bind them.<\/p>\n<p>To fix this, I had to rip out the <code>threading<\/code> module and replace it with <code>multiprocessing<\/code>. But <code>multiprocessing<\/code> comes with its own baggage. You have to serialize data (pickle) to send it between processes. Pickle is slow. Pickle is heavy. If you\u2019re sending large objects, you\u2019re back to square one with memory exhaustion because each child process gets its own copy of the memory space (until a write triggers Copy-on-Write).<\/p>\n<h2><span class=\"ez-toc-section\" id=\"DATABASE_TRACE_SQLALCHEMY_2021_AND_THE_N1_APOCALYPSE\"><\/span>DATABASE TRACE: SQLALCHEMY 2.0.21 AND THE N+1 APOCALYPSE<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>While the <strong>python code<\/strong> was struggling with its own internal memory, it was also hammering our database into submission. I looked at the PostgreSQL slow query logs. <\/p>\n<pre class=\"codehilite\"><code class=\"language-sql\">SELECT users.id, users.name FROM users WHERE users.id = 123;\nSELECT users.id, users.name FROM users WHERE users.id = 124;\nSELECT users.id, users.name FROM users WHERE users.id = 125;\n<\/code><\/pre>\n<p>Kevin had implemented a classic N+1 query pattern. For every <code>ActivityLog<\/code> he processed, his <strong>python code<\/strong> would reach out to the database to fetch the associated <code>User<\/code> object. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\"># The N+1 disaster\nfor log in logs:\n    print(f&quot;User {log.user.name} did something&quot;) # This log.user.name triggers a new query\n<\/code><\/pre>\n<p>In SQLAlchemy 2.0.21, you have to be explicit about your joins. Kevin wasn&#8217;t. He was relying on &#8220;lazy loading,&#8221; which is a fancy way of saying &#8220;I want my database to die a slow death.&#8221; <\/p>\n<p>I had to rewrite the query to use <code>joinedload<\/code> or <code>subqueryload<\/code>. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\">query = session.query(ActivityLog).options(joinedload(ActivityLog.user)).filter(...)\n<\/code><\/pre>\n<p>But even then, the <strong>python code<\/strong> was still too slow. The overhead of converting SQL rows into Python objects is non-trivial. When you\u2019re dealing with millions of rows, the &#8220;Object-Relational&#8221; part of ORM becomes a massive tax. I ended up bypassing the ORM entirely for the heavy lifting, using raw SQL and fetching results as simple tuples. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\"># Stripping away the &quot;magic&quot;\nresults = session.execute(text(&quot;SELECT l.id, u.name FROM activity_logs l JOIN users u ON l.user_id = u.id&quot;)).fetchall()\n<\/code><\/pre>\n<p>The memory usage dropped instantly. A tuple of primitives is significantly smaller than a full-blown SQLAlchemy model instance. The <strong>python code<\/strong> started to behave. But I wasn&#8217;t done.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"RESOLUTION_STRIPPING_THE_ABSTRACTIONS_TO_THE_BONE\"><\/span>RESOLUTION: STRIPPING THE ABSTRACTIONS TO THE BONE<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>By hour thirty-six, I had the memory under control and the GIL contention minimized. But the script was still taking too long to finish. The &#8220;clever&#8221; logic Kevin had written involved a lot of string manipulation and datetime parsing. <\/p>\n<p>In Python, strings are immutable. Every time you do <code>s += \"new bit\"<\/code>, you\u2019re creating a new string object and copying the old one. Kevin\u2019s <strong>python code<\/strong> was doing this inside a loop that ran millions of times. <\/p>\n<p>I replaced his string concatenations with a list of strings and a <code>\"\".join(list_of_strings)<\/code> at the end. It\u2019s a basic optimization, but it\u2019s one that people who care more about &#8220;elegance&#8221; than &#8220;execution&#8221; always seem to forget. <\/p>\n<p>Then there was the datetime parsing. <code>datetime.strptime<\/code> is notoriously slow because it has to handle all the complexities of locales and formats. I replaced it with a custom parser that just sliced the string, since our logs are in a fixed ISO format. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\"># Fast ISO parsing\ndef fast_parse(ts_str):\n    # ts_str is &quot;2023-10-27T12:00:00&quot;\n    return datetime(int(ts_str[:4]), int(ts_str[5:7]), int(ts_str[8:10]), ...)\n<\/code><\/pre>\n<p>This shaved another 20% off the execution time. <\/p>\n<p>But the real win came from using <code>mmap<\/code>. I realized that instead of loading the log files into memory at all, I could just map them into the process&#8217;s address space. This lets the OS handle the paging. If the <strong>python code<\/strong> needs a specific byte, the kernel fetches that page from disk. If memory gets tight, the kernel can just drop the page because it\u2019s backed by a file. <\/p>\n<pre class=\"codehilite\"><code class=\"language-python\">import mmap\n\nwith open(&quot;huge_log.txt&quot;, &quot;r+b&quot;) as f:\n    mm = mmap.mmap(f.fileno(), 0)\n    # Now we can treat 'mm' like a giant bytearray without loading it all\n<\/code><\/pre>\n<p>I also looked into the <code>__slots__<\/code> optimization for our internal data structures. By default, Python objects use a dictionary to store their attributes. This allows for the flexibility of adding new attributes at runtime, but it\u2019s a memory disaster. By defining <code>__slots__<\/code>, we tell Python exactly what attributes an object will have, allowing it to use a fixed-size array instead of a dictionary.<\/p>\n<pre class=\"codehilite\"><code class=\"language-python\">class ProcessedRecord:\n    __slots__ = ['id', 'user_id', 'timestamp', 'action_code']\n    def __init__(self, id, user_id, timestamp, action_code):\n        self.id = id\n        self.user_id = user_id\n        self.timestamp = timestamp\n        self.action_code = action_code\n<\/code><\/pre>\n<p>This change alone reduced the memory footprint of our record objects by nearly 60%. When you\u2019re dealing with millions of these things, that\u2019s the difference between a stable system and a 3 AM wake-up call.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"THE_AFTERMATH_LESSONS_IN_STABILITY\"><\/span>THE AFTERMATH: LESSONS IN STABILITY<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>It\u2019s now 5:00 AM on Tuesday. The script is running. It\u2019s processing the entire backlog at a rate of 50,000 records per second. The memory usage is a flat line at 4GB. The CPU usage is evenly distributed across all cores thanks to a properly implemented <code>multiprocessing<\/code> pool. <\/p>\n<p>I\u2019ve spent the last two days fixing <strong>python code<\/strong> that should have never passed a code review. But we don&#8217;t have time for thorough reviews when we&#8217;re &#8220;moving fast and breaking things.&#8221; Well, things broke. They broke hard.<\/p>\n<p>The problem with modern software development is that we\u2019ve become too comfortable with abstractions. We think that because we\u2019re writing in a high-level language, we don&#8217;t need to understand how the kernel manages memory or how the CPU schedules tasks. We treat the interpreter like a black box that will magically handle our inefficiencies. <\/p>\n<p>But the black box has limits. The GIL is real. The GC overhead is real. The cost of a <code>PyObject<\/code> is real. <\/p>\n<p>I\u2019m looking at the final <code>pip freeze<\/code> of the patched environment:<\/p>\n<pre class=\"codehilite\"><code class=\"language-text\">SQLAlchemy==2.0.21\npsycopg2-binary==2.9.9\nnumpy==1.26.1\npython-dateutil==2.8.2\n<\/code><\/pre>\n<p>I added <code>numpy<\/code> because, frankly, if you\u2019re doing heavy numerical processing or large-scale data manipulation, you shouldn&#8217;t be using pure <strong>python code<\/strong> anyway. You should be using something that drops down into C and manages its own memory buffers.<\/p>\n<p>I\u2019m going home now. I\u2019m going to sleep for fourteen hours. When I come back, I\u2019m going to have a very long, very unpleasant conversation with Kevin about the difference between &#8220;clever&#8221; code and &#8220;production&#8221; code. <\/p>\n<p>If I see one more list comprehension being used to load a multi-gigabyte dataset, I\u2019m revoking everyone&#8217;s <code>sudo<\/code> access and moving the entire stack to assembly. At least then, people will have to think about where their bytes are going. <\/p>\n<p>The system is stable. The alerts are silent. The &#8220;magic&#8221; is gone, replaced by boring, predictable, and efficient logic. That\u2019s how it should be. Stability isn&#8217;t a feature; it\u2019s a prerequisite. And if your <strong>python code<\/strong> can&#8217;t respect the hardware it runs on, it doesn&#8217;t belong in my data center.<\/p>\n<p>I\u2019m out. Don\u2019t page me. Unless the building is literally on fire, and even then, check the temperature sensors first. I don&#8217;t trust &#8220;clever&#8221; fire alarms either. They probably run on a micro-service architecture with a 500ms latency. <\/p>\n<p>End of report.<\/p>\n<pre class=\"codehilite\"><code class=\"language-bash\"># Final status check\n$ uptime\n 05:12:01 up 2 days, 14:22,  1 user,  load average: 0.05, 0.12, 0.15\n$ free -h\n              total        used        free      shared  buff\/cache   available\nMem:           62Gi       4.2Gi        48Gi       1.0Mi        10Gi        57Gi\nSwap:         2.0Gi          0B       2.0Gi\n<\/code><\/pre>\n<p>The numbers don&#8217;t lie. The &#8220;elegant&#8221; code is in the trash, and the &#8220;ugly&#8221; code is actually working. I&#8217;ll take ugly and working over elegant and broken any day of the week. Especially on a Sunday at 3 AM. <\/p>\n<p>Now, where is my coffee? Actually, forget the coffee. I need a drink that\u2019s stronger than my hatred for unoptimized bytecode. <\/p>\n<p>The outage is over. The autopsy is complete. The cause of death was &#8220;Cleverness.&#8221; The cure was &#8220;Reality.&#8221; <\/p>\n<p>Goodnight. Or good morning. Whatever. Just stay off my servers.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Related_Articles\"><\/span>Related Articles<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Explore more insights and best practices:<\/p>\n<ul>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/master-docker-compose-simplify-multi-container-workflows\/\">Master Docker Compose Simplify Multi Container Workflows<\/a><\/li>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/how-to-install-zabbix-server-on-ubuntu-18-04-16-04-lts\/\">How To Install Zabbix Server On Ubuntu 18 04 16 04 Lts<\/a><\/li>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/enable-rcs-message-in-any-android-phone\/\">Enable Rcs Message In Any Android Phone<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>text Traceback (most recent call last): File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 442, in main() File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in main results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 89, in process_record buffer.append(deep_copy_transform(r)) MemoryError [ 172834.123456] Out of memory: Kill process 12834 (python3.11) score &#8230; <a title=\"Mastering Python Code: Tips, Tricks, and Best Practices\" class=\"read-more\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\" aria-label=\"Read more  on Mastering Python Code: Tips, Tricks, and Best Practices\">Read more<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4891","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale\" \/>\n<meta property=\"og:description\" content=\"text Traceback (most recent call last): File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 442, in main() File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in main results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 89, in process_record buffer.append(deep_copy_transform(r)) MemoryError [ 172834.123456] Out of memory: Kill process 12834 (python3.11) score ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\" \/>\n<meta property=\"og:site_name\" content=\"ITSupportWale\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Itsupportwale-298547177495978\" \/>\n<meta property=\"article:published_time\" content=\"2026-09-26T18:29:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2021\/05\/android-chrome-512x512-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"512\" \/>\n\t<meta property=\"og:image:height\" content=\"512\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Techie\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Techie\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\"},\"author\":{\"name\":\"Techie\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d\"},\"headline\":\"Mastering Python Code: Tips, Tricks, and Best Practices\",\"datePublished\":\"2026-09-26T18:29:11+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\"},\"wordCount\":1981,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\",\"url\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\",\"name\":\"Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale\",\"isPartOf\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#website\"},\"datePublished\":\"2026-09-26T18:29:11+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/itsupportwale.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Mastering Python Code: Tips, Tricks, and Best Practices\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#website\",\"url\":\"https:\/\/itsupportwale.com\/blog\/\",\"name\":\"ITSupportWale\",\"description\":\"Tips, Tricks, Fixed-Errors, Tutorials &amp; Guides\",\"publisher\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/itsupportwale.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\",\"name\":\"itsupportwale\",\"url\":\"https:\/\/itsupportwale.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png\",\"contentUrl\":\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png\",\"width\":1119,\"height\":144,\"caption\":\"itsupportwale\"},\"image\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/Itsupportwale-298547177495978\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d\",\"name\":\"Techie\",\"sameAs\":[\"https:\/\/itsupportwale.com\",\"iswblogadmin\"],\"url\":\"https:\/\/itsupportwale.com\/blog\/author\/iswblogadmin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/","og_locale":"en_US","og_type":"article","og_title":"Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale","og_description":"text Traceback (most recent call last): File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 442, in main() File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in main results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 118, in results = [process_record(r) for r in large_dataset_query] File &#8220;\/opt\/deploy\/services\/analytics\/processor.py&#8221;, line 89, in process_record buffer.append(deep_copy_transform(r)) MemoryError [ 172834.123456] Out of memory: Kill process 12834 (python3.11) score ... Read more","og_url":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/","og_site_name":"ITSupportWale","article_publisher":"https:\/\/www.facebook.com\/Itsupportwale-298547177495978","article_published_time":"2026-09-26T18:29:11+00:00","og_image":[{"width":512,"height":512,"url":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2021\/05\/android-chrome-512x512-1.png","type":"image\/png"}],"author":"Techie","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Techie","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#article","isPartOf":{"@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/"},"author":{"name":"Techie","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d"},"headline":"Mastering Python Code: Tips, Tricks, and Best Practices","datePublished":"2026-09-26T18:29:11+00:00","mainEntityOfPage":{"@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/"},"wordCount":1981,"commentCount":0,"publisher":{"@id":"https:\/\/itsupportwale.com\/blog\/#organization"},"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/","url":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/","name":"Mastering Python Code: Tips, Tricks, and Best Practices - ITSupportWale","isPartOf":{"@id":"https:\/\/itsupportwale.com\/blog\/#website"},"datePublished":"2026-09-26T18:29:11+00:00","breadcrumb":{"@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/itsupportwale.com\/blog\/mastering-python-code-tips-tricks-and-best-practices\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/itsupportwale.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Mastering Python Code: Tips, Tricks, and Best Practices"}]},{"@type":"WebSite","@id":"https:\/\/itsupportwale.com\/blog\/#website","url":"https:\/\/itsupportwale.com\/blog\/","name":"ITSupportWale","description":"Tips, Tricks, Fixed-Errors, Tutorials &amp; Guides","publisher":{"@id":"https:\/\/itsupportwale.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/itsupportwale.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/itsupportwale.com\/blog\/#organization","name":"itsupportwale","url":"https:\/\/itsupportwale.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png","contentUrl":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png","width":1119,"height":144,"caption":"itsupportwale"},"image":{"@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Itsupportwale-298547177495978"]},{"@type":"Person","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d","name":"Techie","sameAs":["https:\/\/itsupportwale.com","iswblogadmin"],"url":"https:\/\/itsupportwale.com\/blog\/author\/iswblogadmin\/"}]}},"_links":{"self":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts\/4891","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/comments?post=4891"}],"version-history":[{"count":0,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts\/4891\/revisions"}],"wp:attachment":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/media?parent=4891"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/categories?post=4891"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/tags?post=4891"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}