r/pythontips • • 7h ago

Long_video Giving back to the community - The Complete Backend Development Course (last round)

2 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 • • 1d ago

Module Keep an architecture migration exception on the import that needs it

3 Upvotes

A migration exception is easier to review when it sits next to the import that needs it.

I maintain ArchUnitPython. For a known compatibility shim, it supports an inline directive:

from app.adapters.store import Store  # archunit: ignore

That import edge is omitted from the architecture analysis. You don't have to exclude the entire module from every rule just to keep that one temporary dependency working.

I checked the same import with and without the directive against a domain-to-adapter boundary. The ordinary import failed. The annotated import was excluded.

Treat this as a visible exception, not a way to declare the design fixed. Add a reason in a nearby comment and remove the directive with the migration. The rest of the module should still be checked.

It's useful when a rule is worth enforcing now but one old call site cannot be moved in the same change.

Source: https://github.com/LukasNiessen/ArchUnitPython


r/pythontips • • 2d ago

Standard_Lib Tip: lstrip("test_") doesn’t remove the prefix “test_”. Use removeprefix instead

3 Upvotes

strip, lstrip and rstrip don’t take a prefix or suffix. They take a set of characters and remove any of them from the edge. That looks right on some inputs and silently breaks on others:

>>> "docs.csv".rstrip(".csv")
'do'

>>> "settings".lstrip("test_")
'ings'

In the first one, .csv is treated as the characters ., c, s, v, so the s and c at the end of docs get eaten too. In the second, s, e, t and _ are all in the set, so settings loses its first four letters.

Part of what makes this a trap is that it often works by coincidence:

>>> "test_utils.py".lstrip("test_")
'utils.py'

Since Python 3.9 there are methods that do what people usually mean:

>>> "settings".removeprefix("test_")
'settings'

>>> "test_utils.py".removeprefix("test_")
'utils.py'

>>> "docs.csv".removesuffix(".csv")
'docs'

They remove the exact string once, and only if it’s there. If the prefix or suffix isn’t present, you get the original string back, and repeating isn’t a problem:

>>> "report.csv.csv".removesuffix(".csv")
'report.csv'

When to still use strip**:** when you really want to trim a set of characters, like whitespace or punctuation (line.strip() or text.strip(".,;")).

Compatibility: on Python versions before 3.9, removeprefix and removesuffix don’t exist. A small helper using startswith and slicing does the same job.

Do you have a favorite “looks right, works by coincidence” Python trap?


r/pythontips • • 4d ago

Module PyLings: Solve Exercises and Learn Python

3 Upvotes

https://github.com/thesayfulla/pylings

Learn Python by fixing code: exercises from basics to senior.


r/pythontips • • 5d ago

Syntax unittest or pytest

3 Upvotes
Do you prefer pytest or unittest?

r/pythontips • • 5d ago

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

5 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 • • 7d ago

Module Tip: distinguish TYPE_CHECKING imports from runtime dependencies in architecture tests

2 Upvotes

When you check import boundaries, TYPE_CHECKING imports deserve a deliberate choice.

For example, a file can import a type under if TYPE_CHECKING: without importing that module at runtime. There's still a relationship between the types, but you may not want it to count when a rule is specifically about runtime coupling.

I maintain ArchUnitPython. It has an opt-in setting for exactly that distinction:

from archunitpython import CheckOptions, project_files, assert_passes

def test_domain_does_not_import_infrastructure_at_runtime():
    rule = (
        project_files("src/")
        .in_path("**/domain/**")
        .should_not()
        .depend_on_files()
        .in_path("**/infrastructure/**")
    )
    assert_passes(
        rule,
        CheckOptions(ignore_type_checking_imports=True),
    )

Here src/ is the import root. Imports from domain files into infrastructure files are checked, while imports inside if TYPE_CHECKING: are excluded from the analysis.

An ordinary runtime import still fails the rule. That lets you keep the dependency check without treating every type hint as runtime coupling.

Leave the option off if your architectural boundary is meant to forbid type-level dependencies too. The useful part is being explicit about which relationship the test is protecting.

Source: https://github.com/LukasNiessen/ArchUnitPython


r/pythontips • • 8d ago

Standard_Lib Internals of asyncio

2 Upvotes

This article is a deep dive into the internals of the asyncio Python standard library. It is written from a debugging perspective, stepping through the code line by line.

Article: [internals of asyncio](https://origintracer.app/excerpt/asyncio-internals/)


r/pythontips • • 9d ago

Long_video Giving back to the community - The Complete Backend Development Course (Round 5)

4 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

Algorithms Automating Data Preprocessing: A Guide to Python AI Data Cleaning

3 Upvotes

Data cleaning usually eats up most of a data scientist's time, often exceeding seventy percent of a project lifecycle. Manually writing custom regex filters and handling edge cases for missing values quickly becomes tedious.

​To fix this bottleneck, I put together a deep dive on leveraging machine learning workflows to automate dataset refinement. The complete guide covers setting up intelligent pipelines, handling anomalies, and standardizing features efficiently using modern Python libraries.

​If you want to streamline your preprocessing workflow and spend more time on actual modeling, you can check out the full breakdown here: https://interconnectd.com/blog/124/python-ai-data-cleaning-the-complete-refinement-guide/

What automated tools or libraries do you currently use to speed up your data cleaning pipeline?


r/pythontips • • 10d ago

Meta Tip: when to use a sampling profiler, and which one

3 Upvotes

cProfile runs extra code on every function call and return. That slows your program down, and it slows down code that makes many small calls far more than code that makes a few big ones. So it doesn't just make everything slower; it also skews the picture of which parts are slow.

The numbers can be large. A 2022 study of Python profilers by the Scalene team found cProfile added about 73% to run time, and one tracing profiler reported a function taking 80% of the time when it actually took 25%.

A sampling profiler looks at the call stack at regular intervals instead, so your code runs at close to normal speed and the timings reflect how it really behaves. Some options:

py-spy record -o profile.svg -- python script.py
austin -o profile.mojo python script.py (then open it in e.g. the VS Code extension)
python -m profiling.sampling run script.py (built into Python 3.15+)

Most of them can also attach to a process that's already running, e.g. austin -p 1234.

When cProfile is still the right tool: when you need exact call counts ("was this called 1,204 times?"). For "where does the time go?", use a sampling profiler instead!

Disclosure: I maintain Austin. I wrote a longer comparison of the current Python profilers (Tachyon, py-spy, Scalene, Austin) here, if you want more details: https://p403n1x87.github.io/the-state-of-python-profiling-in-2026.html


r/pythontips • • 12d ago

Syntax Tip: use timedelta for durations so a bare 30 never means seconds in one place and milliseconds in another

20 Upvotes

A number like timeout = 30 doesn’t say its unit. One function may treat it as seconds and another as milliseconds, and nothing complains.

import time

def wait(timeout):
    time.sleep(timeout)      # seconds

wait(400)                    # meant 400 ms, sleeps almost 7 minutes

Make the unit part of the value by passing a timedelta:

import time
from datetime import timedelta

def wait(duration: timedelta):
    time.sleep(duration.total_seconds())

wait(timedelta(milliseconds=400))   # sleeps 0.4 s
wait(timedelta(seconds=30))         # sleeps 30 s

Now the call site says what it means, and a bare wait(400) fails (a timedelta is expected, so duration.total_seconds() raises on an int).

Durations also combine nicely:

total = timedelta(minutes=2) + timedelta(seconds=30)
print(total.total_seconds())   # 150.0

Notes:

  • Convert to a plain number only at the boundary, where a library needs one (time.sleep takes seconds).

  • A timedelta is a fixed length of time, not a calendar period, so “one month” or “next day at 9:00” aren’t durations in this sense.

  • If you can’t use timedelta, putting the unit in the name (timeout_seconds) is the cheap alternative.


r/pythontips • • 14d ago

Module [Python C extension] numagr v0.9

3 Upvotes

A Python C extension for statistics and number aggregation designed to work with both plain int and float objects, as well as with Python numeric strings without having to construct intermediate Python objects to hold their values - useful for large collections that need to be parsed as fast as possible - like trading data.

It outperforms both std Python modules and numpy for both plain numbers and for numeric strings.

https://github.com/andrzejs-gh/numagr

https://pypi.org/project/numagr (source and Windows wheels for 3.11, 3.12, 3.13, 3.14, 3.15)

pip install numagr

This is an early version offering basic methods, I will be developing it further if I find the time. Feedback, improvement suggestions and bug reports are very much welcome.


r/pythontips • • 15d ago

Syntax Prompt for ai to fix my bf IG code

0 Upvotes

What prompt can I use to help fix my python code?


r/pythontips • • 16d ago

Python3_Specific I built psp, a Rust-powered tool for scaffolding Python projects — feedback welcome

6 Upvotes

Hello everyone! I’ve been working on psp (Python Scaffolding Projects), a command-line tool that helps set up new Python projects without the need to manually assemble every single component. It is written in Rust but designed specifically for Python developers.

Depending on your needs, it can create a project structure and a pyproject.toml file, set up a virtual environment, install dependencies, and add common elements such as tests, documentation, CI configuration, Git files, and project documentation. It supports various tools and workflows within the Python ecosystem—including pip, conda, and uv—as well as build systems like Hatch, Maturin, and Poetry. You can also choose between "quick," "simple," or "full" configuration options, and customize the generated project using profiles and templates.

Here is an example of the type of project structure it can produce:

dream/
├── pyproject.toml
├── README.md
├── CHANGES.md
├── LICENSE.md
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── Dockerfile
├── Containerfile
├── Makefile
├── requirements.txt
├── .circleci/
│ └── config.yml
└── docs/

└── source/

├── conf.py

└── index.rst

The exact files and structure depend on the choices made during setup; the tree structure shown above is just an example taken from the project's documentation.

I would love to get feedback from those who regularly create Python packages or applications: what do you typically include in a new project? Which parts would you prefer to configure interactively, and which do you prefer to keep minimal? I am particularly interested in hearing your thoughts on the workflow and how psp compares to tools like Cookiecutter, Copier, or PyScaffold.

Repository: https://github.com/MatteoGuadrini/psp Documentation: https://psp.readthedocs.io/

Thanks for taking a look!


r/pythontips • • 16d ago

Syntax A fill-in-the-blank template for asking for help with a bug

5 Upvotes

zip() stops at the shortest input and says nothing. If two lists were supposed to have the same length and one doesn’t, you lose items without any warning.

names = ["Ana", "Bruno", "Carla"]
scores = [90, 80]

print(list(zip(names, scores)))
# [('Ana', 90), ('Bruno', 80)]   <- Carla disappeared, no error

Since Python 3.10, you can ask for the lengths to match:

print(list(zip(names, scores, strict=True)))
# ValueError: zip() argument 2 is shorter than argument 1

Now the bug shows up where it happens, not later as a missing row in a report.

Notes:

  • strict needs Python 3.10 or newer.

  • If truncation is what you want, leave strict off, so the code says what it means. If you want to keep all items and fill in the gaps, use itertools.zip_longest.

  • With lazy iterators (generators), the error is raised when the shorter one runs out, not at the start.

Use it whenever the inputs are supposed to line up, such as a list of names and a list of values built separately.


r/pythontips • • 16d ago

Long_video Giving back to the community - The Complete Backend Development Course (Round 4)

4 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 • • 23d ago

Long_video Giving back to the community - The Complete Backend Development Course (Round 3)

18 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 • • 23d ago

Module I built Python Workflow Automation Lab: A collection of practical scripts for GUI automation and repetitive task handling

2 Upvotes

I built Python Workflow Automation Lab to streamline repetitive desktop tasks, handle window focus, and automate GUI workflows using Python. It features practical scripts and a clean interface.

It's free, open-source, and available here:
LAB


r/pythontips • • 29d ago

Long_video Giving back to the community - The Complete Backend Development Course (Round 2)

8 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 • • Oct 06 '26

Module django-admin-mcp: Expose Django admin to AI agents with one mixin

0 Upvotes

Hi I built this because I wanted an agent to do the things I already do

in Django admin, without writing a separate API for it.

You add a mixin to a ModelAdmin and it becomes MCP tools over HTTP: CRUD,

bulk operations, admin actions, change history, FK autocomplete.

A few design choices:

- Only two dependencies: Django and Pydantic. No MCP SDK; the protocol is

implemented directly.

- It reuses Django's permission system. Tokens start with no access, you

grant permissions/groups per token, and a token can never exceed its

linked user's permissions.

- Writes go through the admin's own pipeline, so they show up in the admin

history log under that user.

- Sensitive fields can be excluded per model (mcp_exclude_fields).

Happy to hear where the permission model or tool design falls short.

https://github.com/7tg/django-admin-mcp


r/pythontips • • Oct 05 '26

Module Hard Python Dictionary Exercise

4 Upvotes

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

    # Output of this Python Program?
    a = {1: []}
    b = a
    b |= {2: []}
    b[1].append(100)
    b = b | {3: []}
    b[2].append(200)
    b[3].append(300)

    print(a)
    # --- possible answers --- 
    # A) {1: []}
    # B) {1: [100], 2: []}
    # C) {1: [100], 2: [200]}
    # D) {1: [100], 2: [200], 3: []}
    # E) {1: [100], 2: [200], 3: [300]}

The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening.


r/pythontips • • Oct 05 '26

Syntax Find anomalies in this code

0 Upvotes

import base64

import pandas as pd

from pydantic import ValidationError

def process_spreadsheet_with_legacy_safeguards(file_path_or_buffer):

"""

Imports .xls or CSV data dumps from legacy systems, captures strict length

metrics for anomaly detection, and handles binary BLOB substitutions.

"""

# Read spreadsheet explicitly handling encoding where applicable

df = pd.read_excel(file_path_or_buffer)

records = df.to_dict(orient="records")

normalized_records = []

for row in records:

clean_row = {}

for k, v in row.items():

normalized_key = str(k).strip()

if pd.isna(v):

clean_row[normalized_key] = None

elif isinstance(v, bytes):

# If binary data is passed, convert to Base64 string for safe JSON transport

clean_row[normalized_key] = base64.b64encode(v).decode('utf-8')

elif isinstance(v, str):

# Ensure proper UTF-8 handling and strip trailing EBCDIC/ASCII padding artifacts

clean_row[normalized_key] = v.strip()

else:

# Handle numeric coercions (e.g., spreadsheet floats like 1048576.0 -> int)

clean_row[normalized_key] = v

normalized_records.append(clean_row)

return normalized_records

def validate_and_capture_lengths(records: list):

"""

Validates records against the DTO and logs exact field lengths

instead of just item counts to catch truncation and packing anomalies.

"""

anomalies = []

for index, record in enumerate(records):

try:

CustomerResponseSchema.model_validate(record)

except ValidationError as err:

# Capture detailed metadata including exact length of every field

field_length_metrics = {}

for k, v in record.items():

if isinstance(v, str):

field_length_metrics[k] = {"length": len(v), "preview": v[:20]}

elif v is None:

field_length_metrics[k] = {"length": 0, "value": "null"}

else:

field_length_metrics[k] = {"length": len(str(v)), "value": v}

anomalies.append({

"record_index": index,

"field_metrics": field_length_metrics, # Replaces simple item counts with actual lengths

"validation_errors": err.errors(),

})

return anomalies


r/pythontips • • Oct 03 '26

Module Python scaffolding projects

0 Upvotes

I built a new Python scaffolding tool called **psp** — it’s written in **Rust** and focused on speed, simplicity, and a better developer experience.

If you’ve ever wanted a lightweight tool for managing Python projects without the usual overhead, this might be worth a look. Rust gives it a strong performance foundation, and the goal is to keep it fast and easy to use.

Repo: https://github.com/MatteoGuadrini/psp

I’d love feedback from the Python community — especially on workflow, usability, and features you’d want in a modern Python tool.

If anyone’s interested, I can also share:

- what problem it solves

- how it compares to existing tools

- the roadmap