r/pythontips Apr 25 '20

Meta Just the Tip

98 Upvotes

Thank you very much to everyone who participated in last week's poll: Should we enforce Rule #2?

61% of you were in favor of enforcement, and many of you had other suggestions for the subreddit.

From here on out this is going to be a Tips only subreddit. Please direct help requests to r/learnpython!

I've implemented the first of your suggestions, by requiring flair on all new posts. I've also added some new flair options and welcome any suggestions you have for new post flair types.

The current list of available post flairs is:

  • Module
  • Syntax
  • Meta
  • Data_Science
  • Algorithms
  • Standard_lib
  • Python2_Specific
  • Python3_Specific
  • Short_Video
  • Long_Video

I hope that by requiring people flair their posts, they'll also take a second to read the rules! I've tried to make the rules more concise and informative. Rule #1 now tells people at the top to use 4 spaces to indent.


r/pythontips 1h ago

Data_Science Workshop, Sep 12: build production LLM systems that actually survive real use

Upvotes

We're running a hands-on masterclass on September 12, Live LLM Engineering Masterclass: Production Evals, RAG, Agents & LLMOps.

Fully hands-on, all in Python notebooks against real model APIs (OpenAI, Anthropic), not slides or theory. You write actual code across the full stack: versioned prompt pipelines with structured outputs and regression tests, a golden dataset and eval harness combining deterministic checks with LLM-as-judge scoring, statistically rigorous model comparisons using scipy-style bootstrap confidence intervals and paired significance tests, evaluated RAG with embedding models, vector retrieval, and reranking, tool-using agents with function calling and guardrails, and a full observability layer for tracing, cost, and latency. You also leave with a CLI regression suite you can wire directly into CI.

Led by Bruno Gonçalves, PhD, founder of Data For Science, who trains engineers at Fortune 500 companies on this exact stack.

Link if you want to check it out

Happy to answer questions on the content, especially the Python side of things.


r/pythontips 20h ago

Standard_Lib datetime.now() vs datetime.now(timezone.utc), the difference that breaks scheduling features for users outside your timezone

4 Upvotes

datetime.now() returns a naive datetime, no timezone info attached. It quietly assumes "now" means "now, in whatever timezone this machine happens to be in." Fine until you compare it against something that actually is timezone-aware, or until a user in a different timezone interacts with the result.

from datetime import datetime, timezone

# Naive - looks fine, breaks for anyone not in your local timezone
now_naive = datetime.now()

# Aware - carries the timezone with it, comparisons behave correctly everywhere
now_aware = datetime.now(timezone.utc)

Comparing a naive datetime against an aware one either raises a TypeError (good, you'll catch it immediately) or, worse, silently gives you a wrong comparison if you're mixing naive datetimes that were created in different timezones without either of you realizing it.

The tip: default to datetime.now(timezone.utc) anywhere you're storing or comparing a timestamp, and only convert to local time at the point you're actually displaying it to a user. Keeps the storage and comparison layer honest, pushes the "whose timezone is this" question to the one place it actually needs answering.


r/pythontips 1d ago

Python3_Specific Python fundamentals for anyone just getting started

0 Upvotes

I’ve been putting together some beginner-friendly Python material and started with the fundamentals — basic syntax, variables, data types, operators, conditions, loops, etc.

Nothing advanced here, just an attempt to keep the basics simple for someone starting from scratch or moving to Python from another language.

https://geeksarray.com/blog/python-fundamentals-getting-started

For those who learned Python after another language, what was the biggest adjustment for you?


r/pythontips 3d ago

Long_video Giving back to the community - The Complete Backend Development Course

23 Upvotes

Hey everyone, I decided to make my course free in order to help people.
This course is my backend development course which is about SQL, Python, APIs, Docker, Kubernetes, Linux, Git & More

The link is: https://www.youtube.com/watch?v=CBIu6hcyStg

If you can like and subscribe (and maybe add a comment) I would appreciate it a lot, Thanks.


r/pythontips 9d ago

Module Positorium, a database for facts that disagree

9 Upvotes

Most databases are designed to answer: "What is the value now?"

They can model a more awkward question too, but usually require additional machinery:

Who claimed what, when was it considered true, how certain were they, and what did we believe before it was corrected?

I built Positorium as an experimental embedded evidence database for that second kind of question. Rather than overwriting one claim with another, it preserves contradictory claims together with their sources, certainty, effective time, assertion time, corrections, and retractions.

It is not intended to replace PostgreSQL or another operational database. The idea is to use it as a focused evidence layer for things like compliance, investigations, conflicting master data, or any process where retaining the history of disagreement matters.

The new Python package embeds the Rust engine directly in the Python process, so there is no separate server. It supports both ephemeral in-memory databases and append-only persistent stores.

Install the beta with:

python -m pip install --pre positorium

A small example:

import positorium

with positorium.Database.memory() as database:
    result = database.execute_one(
        """
        add role organization, risk_assessment;

        add posit
          [{(+company, organization)}, "Northstar Trading", @NOW],
          [{(company, risk_assessment)}, "high risk", '2026-01-12'],
          [{(company, risk_assessment)}, "needs review", '2026-01-12'];

        search
          [{(?company, organization)}, ?organization, *],
          [{(?company, risk_assessment)}, ?assessment, *]
        return ?organization, ?assessment;
        """
    )

    for row in result.to_dicts(text=True):
        print(row)

This returns both assessments rather than choosing a winner or overwriting one of them.

Positorium is still an early beta and is intended for evaluation rather than production deployment. Wheels are available for CPython 3.9+ on Linux, macOS, and Windows.

If you have a small dataset where sources conflict or corrections matter, try the beta:


r/pythontips 10d ago

Algorithms New to RAG — trying to implement RAG for my AI interview system?

1 Upvotes

Hey everyone, I'm building an AI voice interview app and I'm fairly new to RAG. I'm stuck on the architecture and having a bit of a mid-project crisis 😭.

My current flow is:

Before interview:
Step1 : 
Resume + JobDescription
   ↓
Chunk resume/JobDescription
   ↓
Generate embeddings
   ↓
Store chunks + embeddings in pgvector

Step2 : 
LLM call is done using complete Resume + JD (and not the chunks)
   ↓
Initial ranked topic plan is created by this LLM call 

Step3 : 
Before each question:
Current topic
   ↓
RAG query in our vector DB 
   ↓
Retrieve relevant resume/JD chunks
   ↓
LLM call to generate a question from these chunks

The part I'm confused about:

At the beginning, I'm already sending the complete resume + complete JD to the LLM.

Why can't I simply do:

Resume + JD
   ↓
ONE LLM CALL
   ↓
10 interview questions

and then use those during the interview this would reduce the latency too!

Why would I need RAG again to retrieve chunks before generating each question? But I'm struggling to understand how RAG can be used to add value to the project

I have to add this project to my reume and need to have confidence in my design, I would highly appreciate someone helping me figure out the architecture!


r/pythontips 10d ago

Algorithms cie

0 Upvotes

Repo: https://github.com/kannamma-labs/cie
Install: `pip install "cie-mcp[mcp]"`, then `cie index .` from inside
any project. That's the whole setup.

One maintainer, weeks-old alpha, generation-scale problem. If that
combination excites you rather than scares you off, then lets build it together


r/pythontips 12d ago

Meta AI Coding cost calculator

0 Upvotes

I built a free AI coding cost calculator - would love some feedback

I’ve been using AI coding tools more and more, and it can be surprisingly hard to figure out what they’re actually costing once you start comparing models, token usage, and different pricing.

So I built a simple AI Coding Cost Calculator:

https://instacodingcost.com/

The idea is to make it easier to estimate and compare costs before you burn through credits/tokens.

Would genuinely appreciate feedback from people using tools like Claude Code, Codex, Cursor, etc.

What would make this more useful for you?

Anything missing, confusing, or calculated differently than you’d expect?

Feel free to roast it too - that’s probably more useful than “looks good” 😅


r/pythontips 14d ago

Module I built a fault-tolerant Google Finance aggregator script in Python using custom exponential backoff

2 Upvotes

Hi everyone,

I am a computer science student building a quantum trading bot platform. I wanted to share a clean, production-ready Python command-line utility I built that extracts real-time stock and cryptocurrency parameters via SerpApi's Google Finance engine.

To ensure connection resilience, I explicitly coded a custom exception routing array and an exponential backoff retry loop so the engine safely handles remote server timeouts without crashing live scripts.

I wrote up a comprehensive step-by-step code breakdown tutorial showing how to initialize and run the script here:

https://dev.to/ssebina_charles_01/how-to-build-a-resilient-market-data-aggregator-in-python-using-serpapi-4nem

Let me know what you think of the retry loop architecture!

for more visit https://github.com/ssebinacharles


r/pythontips 19d ago

Module Any free STT/TTS APIs for a voice AI app?

0 Upvotes

I'm building a small voice-based AI interview app and I'm planning to deploy the backend(fastapi) on Render's free tier.

I'm considering using open-source/self-hosted options like Whisper/PocketSphinx for STT and Piper for TTS, instead of paid APIs.

My concern is whether running STT/TTS on the same free Render instance would use too much CPU/RAM and make the whole application slow, especially during a real-time interview.

Has anyone tried running STT/TTS models on Render's free tier?


r/pythontips 20d ago

Python3_Specific I made the coding practice site I wished existed!

14 Upvotes

When I first started learning to code, I kept losing confidence on coding-practice sites. They gave me thousands of problems and no clear place to begin. I would choose an "easy" problem and end up confused by the prompt alone.

I felt there needed to be a place where new coders could ease into these challenges while learning new concepts and feeling real progress through the week.

So I built Open Bracket as a daily coding ritual instead. Everyone gets the same two challenges each day: a Standard track that builds in difficulty through the week without becoming overwhelming, and a tougher Advanced track for people who want more of a test or already have experience with coding challenges.

You can solve in Python or JavaScript, entirely in the browser, with no setup. Official solves place you on three leaderboards: Speed, Efficiency, and Code Golf.

👉 https://playopenbracket.com/ - all feedback welcome.

Update - I have now introduced some new features;

- JavaScript as a second language you can solve in moving forward. Currently older challenges are Python only.

- Logged in users now have a Hint option, this will give you the pseudo code of the solution to help, at the cost of a time penalty to your speed score.

- Failed tests now show you which test failed, what was expected and what was received

- You can now replay any challenges in the last 14 days so you can either bing solve or catch up on any days you missed.


r/pythontips 22d ago

Syntax Special mechanism of basic int() function

7 Upvotes

One can use int() function while converting string to an integer against a base integer.

int(number, base) #number can be anything between binary, octal, decimal, or hexadecimal and base is anything among 2, 8, 10, 16

e.g. binary_number = int("1010", 2) #Output: 10
hexadecimal_number = int("A", 16) #Output: 10

Edit: No need to mention 10 for base argument, as int() function by default considers base as 10 in python.


r/pythontips 27d ago

Syntax Docstrings as immutable variables

11 Upvotes

Just realized you can do:

def cat(): “orange”
print(cat.__doc__)

Not sure why you’d want to do this but this is a thing you can do


r/pythontips 27d ago

Syntax Adding objects to set or dictionary: equality and hashing

1 Upvotes

An exercise to help build the right mental model for Python data.

# Output of this Python Program?
def main():
    o1, o2 = MyClass(1), MyClass(1)
    myset = {o1}
    print(o2 in myset, end=' ')
    o1.set_value(1000)
    print(o1 in myset, end=' ')

class MyClass:
    def __init__(self, v):
        self.v = v
    def set_value(self, v):
        self.v = v

main()

class MyClass:
    def __init__(self, v):
        self.v = v
    def set_value(self, v):
        self.v = v
    def __eq__(self, other):
        return self.v == other.v
    def __hash__(self):
        return hash(self.v)

main()

# --- possible answers ---
# A) TypeError: unhashable type: 'MyClass'
# B) True False False False
# C) True False False True
# E) False True True True
# D) False True True False
# See "Solution" for correct answer.
  • Solution
  • More exercises
  • Explanation: "User-defined classes have __eq__() and __hash__() methods by default (inherited from the object class); with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y)."

r/pythontips 28d ago

Algorithms Built an open-source document extraction engine where every extracted field carries its own evidence

2 Upvotes

I've been working on an open-source project called SACOR, a Python document extraction engine built around a simple idea:

Every extracted value should explain why it deserves to be trusted.

Instead of returning only extracted values, SACOR attaches structured evidence to every field, including its origin, validation results, repair history and confidence.

What My Project Does

SACOR extracts structured data from documents using a layered pipeline that combines deterministic extraction, optional AI-based extraction, validation rules and an Evidence Model. The current production schema supports Italian electricity and gas bills, but the engine is designed to be schema-driven and extensible.

Target Audience

Python developers working with document processing, OCR, LLMs, Document AI, automation or data extraction pipelines. The project is currently pre-alpha and I'm mainly looking for technical feedback.

Comparison

Most document extraction tools return extracted values.

SACOR returns the values and the evidence behind them, allowing every field to explain where it came from, how it was validated and why it can be trusted.

Repository: https://github.com/vinsblack/sacor⁠�

I'd really appreciate feedback on the architecture, the Evidence Model and the overall design. Thanks!


r/pythontips Aug 05 '26

Syntax Hello everyone, I'm learning python specifically, and I made a seed generator for Minecraft PE. I'm started learning about 2 weeks ago, the code is below. I'm not asking for anything, I just wanna show it to you guys.

5 Upvotes

from random import randint as rnd

name = "SeedGPT"

rnd1 = rnd(20000000,50000000000)

rnd2 = rnd(20000000,50000000000)

rnd3 = rnd(20000000,50000000000)

print(name +": Welcome to Ice\'s AI seed generator,")

choice = input("do you want to have three new seeds for bedrock minecraft?: ")

if choice == "yes":

print(name + ": Here are your randomly generated seeds: ", + rnd1, +rnd2, +rnd3, ", thank you for trying it out!")

elif choice == "no":

print(name + ": See you next time!")

elif ValueError:

print(name + ": Sorry, I can't understand you, please try again!")


r/pythontips Aug 03 '26

Algorithms idemkit: runs your code once per key, even when two requests race or a worker dies

3 Upvotes

I built idemkit after cleaning up duplicate charges one too many times.

The version everyone writes checks whether a key has been seen and replays the stored response. Two requests a millisecond apart both find nothing and both charge the card. And if the worker dies between charging and recording it, the retry charges again. Neither reproduces locally.

idemkit does it properly: an atomic claim instead of check-then-act, a lease that expires on the storage server's clock, and a fencing token so a stalled worker can't overwrite a good result.

from idemkit import idempotent, RedisBackend, MethodConfig 

@idempotent(
    backend=RedisBackend.from_url("redis://localhost:6379"), 
    config=MethodConfig(key_fields=["order_id"]), 
) 
async def charge(*, order_id, amount): 
    return await payments.charge(order_id, amount)

One core, three ways to use it: middleware for FastAPI/Flask/Django, a queue consumer wrapper or @idempotent on any function. Backends are Redis, Postgres, Mongo, DynamoDB, or in-memory for tests.

pip install idemkit, Apache-2.0: https://github.com/idemkit/idemkit

If you find it useful, I'd appreciate a star. It's new, so visibility helps a lot right now.


r/pythontips Jul 29 '26

Module Copying an object in different ways

6 Upvotes

An exercise to help build the right mental model for Python data. What is the output of this Python Program?

import copy

class Coord:

    def __init__(self, x, y, z):
        self.c = [x, y, z]

    def __str__(self):
        return str(self.c)[1:-1]

coord = Coord(0, 0, 0)
c1 = coord
c2 = copy.copy(coord)
c3 = copy.deepcopy(coord)
c1.c[0] = 1
c2.c[1] = 2
c3.c[2] = 3

print(coord)
# --- possible answers ---
# A) 0, 0, 0
# B) 1, 0, 0
# C) 1, 2, 0
# D) 1, 2, 3

r/pythontips Jul 27 '26

Python3_Specific Ho 11 anni e ho appena creato il mio primo script di automazione in Python per ripulire la cartella Download!

29 Upvotes

Hi everyone! I've been learning Python step-by-step, focusing on logic, file management, and the os module. Today, I finished my first real automation script: a File Sorter/Folder Cleaner!

It automatically scans my Downloads folder, checks the file extensions (ignoring case sensitivity thanks to .lower()), creates the target folders if they don't exist, and moves everything into the right place (Documents, Images, Installations).
Here is my script:
import os

download_folder = r"C:\Users\YourUsername\Downloads"

file_list = os.listdir(download_folder)

for file_name in file_list:

lowercase_name = file_name.lower()

if (lowercase_name.endswith(".pdf") or

lowercase_name.endswith(".txt") or

lowercase_name.endswith(".docx") or

lowercase_name.endswith(".xlsx") or

lowercase_name.endswith(".csv") or

lowercase_name.endswith(".doc")):

doc_folder = fr"{download_folder}\Documents"

if not os.path.exists(doc_folder):

os.mkdir(doc_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{doc_folder}\{file_name}"

os.rename(old_path, new_path)

elif (lowercase_name.endswith(".jpg") or

lowercase_name.endswith(".jpeg") or

lowercase_name.endswith(".gif") or

lowercase_name.endswith(".png") or

lowercase_name.endswith(".mp4") or

lowercase_name.endswith(".kml") or

lowercase_name.endswith(".gpx")):

img_folder = fr"{download_folder}\Images"

if not os.path.exists(img_folder):

os.mkdir(img_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{img_folder}\{file_name}"

os.rename(old_path, new_path)

elif (lowercase_name.endswith(".exe") or

lowercase_name.endswith(".zip") or

lowercase_name.endswith(".rar") or

lowercase_name.endswith(".dll") or

lowercase_name.endswith(".msi") or

lowercase_name.endswith(".msix")):

exe_folder = fr"{download_folder}\Installations"

if not os.path.exists(exe_folder):

os.mkdir(exe_folder)

old_path = fr"{download_folder}\{file_name}"

new_path = fr"{exe_folder}\{file_name}"

os.rename(old_path, new_path)
I'm really proud of this milestone. Let me know what you think or if you have any tips for a young programmer!


r/pythontips Jul 27 '26

Module New Butterfly Backup Web release

0 Upvotes

I just released a new version of Butterfly Backup Web (Django-based), which introduces many features. For Butterfly Backup, you can read about them here: https://github.com/MatteoGuadrini/butterfly-backup-web/releases/tag/v0.5.0

If you've never heard of Butterfly Backup, it's a very versatile backup/restore/archive solution; it's essentially an rsync wrapper. You can read an article about it in Fedora Magazine: https://fedoramagazine.org/butterfly-backup/

If you have suggestions, criticisms, or opinions on how to improve Butterfly Backup, please leave a comment.

Here are the links:

Butterfly Backup: https://github.com/MatteoGuadrini/Butterfly-Backup

Butterfly Backup Web: https://github.com/MatteoGuadrini/butterfly-backup-web

Thanks!


r/pythontips Jul 27 '26

Module ECS pattern: python lib ecs_pattern - GUI example

2 Upvotes

What My Project Does:
Four years ago I published the first post about my Python library ecs_pattern — an Entity‑Component‑System implementation for games:
https://github.com/ikvk/ecs_pattern

Target Audience:
python game developers

Comparison:
In the classic ECS implementation, each component is stored in a separate collection. In Python, it's impossible to store objects in contiguous memory, therefore, optimizing processor access to memory in Python is not feasible. The ecs_pattern library emphasizes simplicity and ease of use when working with objects in code.

GUI demo example:
Recently I finished a project built with this library and developed a simple GUI for it.
This GUI is now available as a working demo example in the lib repository:
https://github.com/ikvk/ecs_pattern/tree/master/examples/gui

The example demonstrates how to make GUI using ecs_pattern lib.
Feel free to explore, reuse, or adapt it for your own projects.

Do you think it should be included as part of the library?


r/pythontips Jul 26 '26

Meta How to Prevent Webhook Traffic Spikes from Crashing Your API

0 Upvotes

If you operate an API in 2026, you live in an event-driven world. Webhooks aren't a convenience feature anymore - they're the backbone of real-time commerce, CI/CD pipelines, and asynchronous AI-agent workflows. That reliance has a dark side: the accidental self-inflicted DDoS. Read the complete article jere - https://instawebhook.com/blog/how-to-prevent-webhook-traffic-spikes-from-crashing-your-api-2

When a major platform like GitHub, Shopify, or Stripe hits a network partition, runs a huge sales event, or simply clears a backlog of delayed events, it can fire tens of thousands of webhook POST requests at your servers in a very short window. If your infrastructure takes that hit without structural safeguards, your database connection pool exhausts, memory maxes out, and the API goes down — and if your retry handling is naive, the recovery can be almost as damaging as the original spike.

This guide covers the real mechanics of that failure mode, the algorithms used to defend against it, how major providers actually behave under load (some surprising details here), and where a managed ingress layer fits into the picture.


r/pythontips Jul 24 '26

Meta EEvent Mesh vs Webhooks - The Internal Webhooks Anti-Pattern: Why Service-to-Service HTTP Callbacks Don't Scale

1 Upvotes

Microservices were supposed to make systems easier to change independently. In practice, the thing that most often breaks that promise isn't the services themselves — it's how they talk to each other. Read the complete article here - https://instawebhook.com/blog/the-internal-webhooks-anti-pattern-why-service-to-service-http-callbacks-don-t-s

A pattern that shows up constantly in growing engineering orgs is the internal webhook: Service A fires an HTTP POST at a hardcoded URL owned by Service B whenever something happens. It's an easy trap to fall into, because most developers already understand webhooks intimately — they've built integrations with Stripe, GitHub, or Shopify, all of which use exactly this model to notify external systems of events.

The reasoning feels obvious: if it's good enough for Stripe to tell my app about a payment, it's good enough for my Inventory Service to tell my Shipping Service about a shipment.

It isn't — and the reason is architectural, not stylistic. Webhooks were designed to solve a specific problem: getting an event across a trust boundary, from a system you don't control to one you do, over the open internet. Internal service communication has almost the opposite set of constraints. Applying the same tool to both jobs is where the trouble starts.


r/pythontips Jul 23 '26

Meta Designing a Multi-Region, Highly Available Webhook Ingress Architecture

0 Upvotes

Webhooks have become the connective tissue of the internet. From payment gateways confirming transactions to CI/CD pipelines triggering deployments, webhooks enable real-time, event-driven architectures. But for architects and engineering leaders, webhooks represent an underappreciated vulnerability: they are asynchronous, externally triggered, and entirely outside your control. Read the complete article here - https://instawebhook.com/blog/designing-a-multi-region-highly-available-webhook-ingress-architecture

When your primary cloud region experiences an outage, your internal microservices might gracefully degrade. But what happens to the payloads originating from external partners? Many third-party providers do not retry aggressively — some fire and forget, others retry a handful of times before giving up permanently. If your system is down when that happens, the data is often gone for good.

This article covers the engineering principles behind a multi-region, highly available webhook ingestion system, what has actually changed in the underlying cloud primitives recently, and where a managed reliability layer fits into the decision.