r/pythontips

I built ArchUnit for Python: enforce architecture rules as unit tests.
▲ 11 r/pythontips+4 crossposts

I built ArchUnit for Python: enforce architecture rules as unit tests.

I just shipped ArchUnitPython, a library that lets you enforce architectural rules in Python projects through automated tests.

The problem it solves: as codebases grow, architecture erodes. Someone imports the database layer from the presentation layer, circular dependencies creep in, naming conventions drift. Code review catches some of it, but not all, and definitely not consistently.

This problem has always existed but is more important than ever in Claude Code, Codex times. LLMs break architectural rules all the time.

So I built a library where you define your architecture rules as tests. Two quick examples:

# No circular dependencies in services
rule = project_files("src/").in_folder("**/services/**").should().have_no_cycles()
assert_passes(rule)
# Presentation layer must not depend on database layer
rule = project_files("src/")
          .in_folder("**/presentation/**")
          .should_not()
          .depend_on_files()
          .in_folder("**/database/**")
assert_passes(rule)

This will run in pytest, unittest, or whatever you use, and therefore be automatically in your CI/CD. If a commit violates the architecture rules your team has decided, the CI will fail.

Hint: this is exactly what the famous ArchUnit Java library does, just for Python - I took inspiration for the name is of course.

Let me quickly address why this over linters or generic code analysis?

Linters catch style issues. This catches structural violations — wrong dependency directions, layering breaches, naming convention drift. It's the difference between "this line looks wrong" and "this module shouldn't talk to that module."

Some key features:

  • Dependency direction enforcement & circular dependency detection
  • Naming convention checks (glob + regex)
  • Code metrics: LCOM cohesion, abstractness, instability, distance from main sequence
  • PlantUML diagram validation — ensure code matches your architecture diagrams
  • Custom rules & metrics
  • Zero runtime dependencies, uses only Python's ast module
  • Python 3.10+

Very curious what you think! https://github.com/LukasNiessen/ArchUnitPython

u/trolleid — 5 days ago

I Require Help For Understanding super()

I understand how to use super() In subclass If they are not Written In init() method.

But If they are Implemented In init() method It becomes hard to read & understand.

Explain me what's happening Under the hood..

I know that init() method has only None return type.

class A:
	def __init__(self, mess="mess_from_A"):
		self.mess = mess

		
class B(A):
	def __init__(self, m):
		super().__init__(m)
		#self.mess


print(B("aditya").mess)
print(B("yash").mess)
reddit.com
u/One-Type-2842 — 7 days ago
▲ 2 r/pythontips+2 crossposts

https://youtu.be/yu2Kav9wBEM

If you have ever run into a NameError, accidentally overwritten a value, or wondered why a variable inside a function does not behave the same as one outside it, this lesson is designed to make that clear.

youtu.be
u/Efficient-Public-551 — 3 days ago

Will This Reduce The Performance Or Makes Little Mistake?

num = [*range(100000)]
random.shuffle(num)
num = sorted(num)
a = ['y',"oefu","nf",'r',"fs","wowo","eqr","jdn","o""g","o","e","p","gsh"]
a = sorted(a)

Is There any Verdict to use the same variable name In line 5?

Will the Above code reduce The Performance If the List has plenty of Elements?

Personally, I Inspect using time.time() func. I seeNo difference If I changed the variable name

reddit.com
u/One-Type-2842 — 18 days ago

[help] Decorators are Hard To Construct

Firstly, Are Decorators useful in Python?

I want Tips to Define Decorators In Python.

I have Already practiced alot on them but still I am Lost.

What I know about them Is It only Decorator The 'return statement' It never Decorate print() function

reddit.com
u/One-Type-2842 — 25 days ago

Is there a Python “formula booklet” (like physics/chem) for syntax?

I’m looking for a PDF or printable booklet, similar to the formula/reactions booklets used in physics and chemistry, but for Python syntax.

Not too detailed—just something quick to look at when I forget syntax. A clean, compact reference I can keep open while coding.

(Bonus: if it also includes some sqlite3 basics like cursor.connect, etc.)

Does something like this exist?
Thanks!

reddit.com
u/Ali2357 — 21 days ago

Programmazione python

Ciao a tutti, sono uno studente del primo anno di ingegneria elettronica e nel piano di studi ho machine learning, si tratta di utilizzare Python per estrapolare risultati da un database. Mi chiedevo, dato che dovrò studiare Python e l’analisi dei dati da solo, se esistesse qualche corso gratuito o di poche decine di euro che fosse buono e desse un certificato valido per aggiungerlo ad un eventuale curriculum. So che esistono molti video su YouTube fatti bene, però volevo qualcosa che desse una certificazione, grazie mille in anticipo

reddit.com
u/True_Concentrate748 — 21 days ago

Python's Mutable and Immutable types

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

    float1 = 0.0  ; float2 = float1
    str1   = "0"  ; str2   = str1
    list1  = [0]  ; list2  = list1
    tuple1 = (0,) ; tuple2 = tuple1
    set1   = {0}  ; set2   = set1

    float2 += 0.1
    str2   += "1"
    list2  += [1]
    tuple2 += (1,)
    set2   |= {1}

    print(float1, str1, list1, tuple1, set1)
    # --- possible answers ---
    # A) 0.0 0 [0] (0,) {0}
    # B) 0.0 0 [0, 1] (0,) {0, 1}
    # C) 0.0 0 [0, 1] (0, 1) {0, 1}
    # D) 0.0 01 [0, 1] (0, 1) {0, 1}
    # E) 0.1 01 [0, 1] (0, 1) {0, 1}

The “Solution” link uses 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵 to visualize execution and reveals what’s actually happening.

reddit.com
u/Sea-Ad7805 — 1 month ago

Real-Time Instance Segmentation using YOLOv8 and OpenCV

For anyone studying Dog Segmentation Magic: YOLOv8 for Images and Videos (with Code):

The primary technical challenge addressed in this tutorial is the transition from standard object detection—which merely identifies a bounding box—to instance segmentation, which requires pixel-level accuracy. YOLOv8 was selected for this implementation because it maintains high inference speeds while providing a sophisticated architecture for mask prediction. By utilizing a model pre-trained on the COCO dataset, we can leverage transfer learning to achieve precise boundaries for canine subjects without the computational overhead typically associated with heavy transformer-based segmentation models.

 

The workflow begins with environment configuration using Python and OpenCV, followed by the initialization of the YOLOv8 segmentation variant. The logic focuses on processing both static image data and sequential video frames, where the model performs simultaneous detection and mask generation. This approach ensures that the spatial relationship of the subject is preserved across various scales and orientations, demonstrating how real-time segmentation can be integrated into broader computer vision pipelines.

Deep-dive video walkthrough: https://youtu.be/eaHpGjFSFYE

 

This content is provided for educational purposes only. The community is invited to provide constructive feedback or post technical questions regarding the implementation details.

 

Eran Feit

u/Feitgemel — 16 days ago

I built a tiny ‘daily score’ app in Python… turns out rating your own life is harder than coding it.

I recently started learning Python and wanted to build something simple but actually useful in real life. So instead of the usual to-do list or habit tracker, I made a small console app where I give my day a score from 0 to 10. That’s it. Just one number per day. The app stores my scores in a file, and shows: all previous scores average score highest and lowest day Sounds super basic, but it made me realize something unexpected… Giving yourself an honest score at the end of the day is surprisingly difficult. Some days feel productive, but then you hesitate: “Was it really a 7… or just a 5?” Also seeing patterns over time is kind of addictive. I’m still a beginner, so the code is pretty simple (functions + file handling). Thinking about adding dates or even a simple graph next. What was the first small project that actually made you reflect on your own habits? And how would you improve something like this?

reddit.com
u/QuantumScribe01 — 28 days ago

YOLOv8 Segmentation Tutorial for Real Flood Detection

For anyone studying computer vision and semantic segmentation for environmental monitoring.

The primary technical challenge in implementing automated flood detection is often the disparity between available dataset formats and the specific requirements of modern architectures. While many public datasets provide ground truth as binary masks, models like YOLOv8 require precise polygonal coordinates for instance segmentation. This tutorial focuses on bridging that gap by using OpenCV to programmatically extract contours and normalize them into the YOLO format. The choice of the YOLOv8-Large segmentation model provides the necessary capacity to handle the complex, irregular boundaries characteristic of floodwaters in diverse terrains, ensuring a high level of spatial accuracy during the inference phase.

The workflow follows a structured pipeline designed for scalability. It begins with a preprocessing script that converts pixel-level binary masks into normalized polygon strings, effectively transforming static images into a training-ready dataset. Following a standard 80/20 data split, the model is trained with specific attention to the configuration of a single-class detection system. The final stage of the tutorial addresses post-processing, demonstrating how to extract individual predicted masks from the model output and aggregate them into a comprehensive final mask for visualization. This logic ensures that even if multiple water bodies are detected as separate instances, they are consolidated into a single representation of the flood zone.

 

Deep-dive video walkthrough: https://youtu.be/diZj_nPVLkE

 

This content is provided for educational purposes only. Members of the community are invited to provide constructive feedback or ask specific technical questions regarding the implementation of the preprocessing script or the training parameters used in this tutorial.

 

#ImageSegmentation #YoloV8

u/Feitgemel — 30 days ago

I built hushlog: A zero-config PII redaction tool for Python logging (Prevents leaking SSNs/Cards in logs)

Hey everyone,

One of the most common (and annoying) security issues in backend development is accidentally logging PII like emails, credit card numbers, or phone numbers. I got tired of writing custom regex filters for every new project's logger, so I built an open-source package to solve it automatically.

It’s called hushlog.

What it does: It provides zero-config PII redaction for Python logging. With just one call to hushlog.patch(), it automatically scrubs sensitive data before it ever hits your console or log files.

Links:

I’d love for you to try it out, tear it apart, and let me know what you think! Any feedback on the codebase, edge cases I might have missed, or feature requests would be incredibly appreciated.

u/felipemorandini — 1 month ago

When To Use __repr__() & __str__() Methods In Python

(Used AI to Improve English)

I understood that Python uses two different methods, repr() and str(), to convert objects into strings, and each one serves a distinct purpose. repr() is meant to give a precise, developer-focused description, while str() aims for a cleaner, user-friendly format. Sometimes I mix them up becuase they look kinda similar at first glance.

I noticed that the Python shell prefers repr() because it helps with debugging and gives full internal details. In contrast, the print() function calls str() whenever it exists, giving me a simpler and more readable output. This difference wasn’t obvious to me at first, but it clicked after a bit.

The example with datetime made the difference pretty clear. Evaluating the object directly showed the full technical representation, but printing it gave a more human-friendly date and time. That contrast helped me understand how Python decides which one to use in different situations.

It also became clear why defining repr() is kinda essential in custom classes. Even if I skip str(), having a reliable repr() still gives me useful info while I’m debugging or checking things in the shell. Without it, the object output just feels empty or useless.

Overall, I realised these two methods are not interchangeable at all. They each solve a different purpose—one for accurate internal representation and one for clean user display—and understanding that difference makes designing Python classes much cleaner and a bit more predictable for me.

reddit.com
u/One-Type-2842 — 25 days ago

Plugin that reviews Python/FastAPI code for architecture issues. Looking for feedback.

What My Project Does: Claude Code plugin that reviews Python/FastAPI code against Clean Architecture principles. Reports issues by severity with file/line references and fix snippets.

Target Audience: Python developers using FastAPI who want automated architecture feedback beyond what linters catch.

Comparison: Linters like ruff and flake8 catch style and syntax. This catches structural problems: business logic in routers, layer skipping, tight coupling, god classes, ABC where Protocol would do.

I built a Claude Code plugin that does architecture reviews on Python/FastAPI code. You run `/review-architecture [path]` and it checks your code against 7 design principles, 17 quality rules, and three-layer architecture compliance, then reports findings by severity with file/line references and fix snippets.

Repo: https://github.com/MKToronto/python-clean-architecture

It catches things linters don't, business logic leaking into routers, layer skipping, ABC where Protocol would do, if/elif chains that should be dict mappings, tight coupling, god classes. Inspired by Arjan Codes, very opinionated toward Pythonic patterns.

Would you use this? What should an architecture reviewer catch that this doesn't?

u/Final_Specialist9965 — 10 hours ago

Boost Your Dataset with YOLOv8 Auto-Label Segmentation

For anyone studying  YOLOv8 Auto-Label Segmentation ,

The core technical challenge addressed in this tutorial is the significant time and resource bottleneck caused by manual data annotation in computer vision projects. Traditional labeling for segmentation tasks requires meticulous pixel-level mask creation, which is often unsustainable for large datasets. This approach utilizes the YOLOv8-seg model architecture—specifically the lightweight nano version (yolov8n-seg)—because it provides an optimal balance between inference speed and mask precision. By leveraging a pre-trained model to bootstrap the labeling process, developers can automatically generate high-quality segmentation masks and organized datasets, effectively transforming raw video footage into structured training data with minimal manual intervention.

 

The workflow begins with establishing a robust environment using Python, OpenCV, and the Ultralytics framework. The logic follows a systematic pipeline: initializing the pre-trained segmentation model, capturing video streams frame-by-frame, and performing real-time inference to detect object boundaries and bitmask polygons. Within the processing loop, an annotator draws the segmented regions and labels onto the frames, which are then programmatically sorted into class-specific directories. This automated organization ensures that every detected instance is saved as a labeled frame, facilitating rapid dataset expansion for future model fine-tuning.

 

Deep-dive video walkthrough: https://youtu.be/tO20weL7gsg

 

This content is for educational purposes only. The community is invited to provide constructive feedback or ask technical questions regarding the implementation or optimization of this workflow.

 

Eran Feit

u/Feitgemel — 8 days ago