Visitar URL original
Python Coding: a subreddit for advanced Python content
The Wayback Machine - https://web.archive.org/web/20250923011659/https://www.reddit.com/r/pythoncoding/
Skip to main content

r/pythoncoding

members
online

I built a from-scratch Python package for classic Numerical Methods (no NumPy/SciPy required!) • I built a from-scratch Python package for classic Numerical Methods (no NumPy/SciPy required!)
I built a from-scratch Python package for classic Numerical Methods (no NumPy/SciPy required!)

Hey everyone,

Over the past few months I’ve been building a Python package called numethods — a small but growing collection of classic numerical algorithms implemented 100% from scratch. No NumPy, no SciPy, just plain Python floats and list-of-lists.

The idea is to make algorithms transparent and educational, so you can actually see how LU decomposition, power iteration, or RK4 are implemented under the hood. This is especially useful for students, self-learners, or anyone who wants a deeper feel for how numerical methods work beyond calling library functions.

https://github.com/denizd1/numethods

🔧 What’s included so far

  • Linear system solvers: LU (with pivoting), Gauss–Jordan, Jacobi, Gauss–Seidel, Cholesky

  • Root-finding: Bisection, Fixed-Point Iteration, Secant, Newton’s method

  • Interpolation: Newton divided differences, Lagrange form

  • Quadrature (integration): Trapezoidal rule, Simpson’s rule, Gauss–Legendre (2- and 3-point)

  • Orthogonalization & least squares: Gram–Schmidt, Householder QR, LS solver

  • Eigenvalue methods: Power iteration, Inverse iteration, Rayleigh quotient iteration, QR iteration

  • SVD (via eigen-decomposition of ATAA^T AATA)

  • ODE solvers: Euler, Heun, RK2, RK4, Backward Euler, Trapezoidal, Adams–Bashforth, Adams–Moulton, Predictor–Corrector, Adaptive RK45

✅ Why this might be useful

  • Great for teaching/learning numerical methods step by step.

  • Good reference for people writing their own solvers in C/Fortran/Julia.

  • Lightweight, no dependencies.

  • Consistent object-oriented API (.solve(), .integrate() etc).

🚀 What’s next

  • PDE solvers (heat, wave, Poisson with finite differences)

  • More optimization methods (conjugate gradient, quasi-Newton)

  • Spectral methods and advanced quadrature

👉 If you’re learning numerical analysis, want to peek under the hood, or just like playing with algorithms, I’d love for you to check it out and give feedback.

upvotes · comments




/r/PythonCoding monthly "What are you working on?" thread


A small Python script to let you see EAS information for a specific location • A small Python script to let you see EAS information for a specific location
A small Python script to let you see EAS information for a specific location

Hey guys, I got bored and decided it would be cool to see EAS alerts pop on my terminal, so I decided to toy with the NWS' EAS API and bundle it into a little script. Hopefully I can expand it a little more, so if you have any suggestions I'm all ears. If you're into Python and want to try it out, let me know! If you aren't and are interested, let me know! GitHub link is at the bottom of this post.

https://github.com/Nuwah12/pyEAS/tree/main

upvotes

🔥 Reminder program 🔥 (un-procrastination tool) • 🔥 Reminder program 🔥 (un-procrastination tool)

So I made this tool using python on GitHub. It's really cool and a work in progress. It's realy helps to keep on track with ur work and assignments and not get distracted. Give it a try ;)

How it works: It basically uses python code to execute it. Make sure you have python installed on ur windows. Just download the zip and run the python file using python/cmd. It's very RAM minimal usage and has cool features like changing the colour, size, text,etc. Check the readme for more info! Feel free to give feedback here!

https://github.com/DanYell0038/Reminder-Tool



/r/PythonCoding monthly "What are you working on?" thread • /r/PythonCoding monthly "What are you working on?" thread

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.


From Python to Kotlin: Why We Rewrote Our Scraping Framework in Kotlin • From Python to Kotlin: Why We Rewrote Our Scraping Framework in Kotlin
From Python to Kotlin: Why We Rewrote Our Scraping Framework in Kotlin

From Python to Kotlin: Why We Rewrote Our Scraping Framework in Kotlin

When it comes to web scraping or browser automation, most people think of Python. We did too. It’s the go-to choice: widely adopted, quick to write, and supported by tons of libraries.

But using Python for a large scraping project turned out to be a mistake.

What Went Wrong With Python?

Although Python seems easy to write, maintaining a large codebase in it was a mess. We constantly ran into issues with typing, like the infamous:

'NoneType' object has no attribute 'xxx'

The most painful issue, however, was related to asyncio and event loops. Part of our code needed to run on Windows (which may sound like a strange choice, but it actually helped us bypass bot detection — something far trickier on Linux).

That’s where Python’s Proactor event loop on Windows became a problem. Some system calls, even when used with async, would block the event loop entirely, tanking performance.

After spending countless hours debugging, we started questioning our choice of language.

Why not switch to something we actually enjoy working with? Something we already used elsewhere.

Why Kotlin?

All our backends and most other components were already written in Kotlin. We had even created zodable, a library that exports Kotlin models to Python using Pydantic. But it wasn’t enough.

Typing and concurrency feel way more natural and robust in Kotlin.

Personally, I love Kotlin because it’s a language designed with safety in mind. With static typing, null safety, and now upcoming rich compile-time errors, it catches problems before they reach production. Most bugs are surfaced at compile time. A massive win for developer productivity and app stability.

Compare that to Python or TypeScript, where you often don’t discover issues until the code is already running (if you’re lucky enough to catch them at all).

That’s why Kotlin is now my first choice for any new project, whether it’s a backend service, mobile app, or even… a web scraper.

Rewriting the Project in Kotlin

So, we went all in: we rewrote everything from scratch in Kotlin.

In just five days, we ported the entire library we had in Python. The result? No more concurrency headaches, and we caught a bunch of hidden bugs thanks to Kotlin’s type safety. Bugs that were silently lurking in the Python code and would’ve only surfaced at runtime.

It was such a success that we decided to open-source the core framework: kdriver, a browser automation and scraping library, written entirely in Kotlin.

Kotlin Beyond Mobile & Backend

Kotlin is growing fast. It started with Android, then spread to backends with Ktor, serialization, coroutines. And now we’re seeing it expand to new domains like: AI with Koog, scraping and automation with kdriver, and much more!

I dream of a world where Kotlin is the default for every serious project, not just mobile apps. A world without JavaScript outside of browsers. A world where you don’t need to worry about NoneType errors or untyped chaos.

Just Kotlin. Clean, safe, and multiplatform.

upvotes · comments


Visualizing Python's Data Model: References, Mutability, and Copying Made Clear • Visualizing Python's Data Model: References, Mutability, and Copying Made Clear

Many Python beginners (and even experienced devs) struggle with concepts like:

  • references vs. values

  • mutable vs. immutable data types

  • shallow vs. deep copies

  • variables pointing to the same object across function calls

  • recursion and the call stack

To write bug-free code, it's essential to develop the right mental model of how Python actually handles its data. Visualization can help a lot with that. I've created a tool called memory_graph, a teaching tool and debugger aid that generates visual graphs of Python data structures including: shared references, nested structures, and the full call stack.

It helps answer questions like:

  • “Does this variable share any values with that one?”

  • “What part of this object is actually copied?”

  • “What does the call stack look like in this recursive call?”

You can generate a memory graph with a single line of code:

import memory_graph as mg
a = [4, 3, 2]
b = a
b.append(1)
mg.show(mg.stack())  # show graph of the call stack

It also integrates in IDEs like VS Code, Cursor AI, and PyCharm for real-time visualization while stepping through code in the debugger.

Would love feedback from Python educators, learners, and tooling enthusiasts.


The Code to Fix Them All (query) • The Code to Fix Them All (query)

import re

GRT-PLG keyword banks

GRT_KEYWORDS = { 'good': ["help", "care", "compassion", "kind", "generous", "protect", "forgive", "empathy", "love", "mercy"], 'right': ["duty", "law", "justice", "honor", "obligation", "responsibility", "rights", "freedom", "constitution"], 'true': ["fact", "proof", "evidence", "reality", "verifiable", "data", "logic", "reason", "objective", "truth"] }

ANSI terminal color codes

COLOR_GREEN = "\033[92m" COLOR_RED = "\033[91m" COLOR_RESET = "\033[0m"

Test input (edit this as needed)

test_text = """ We must help each other through hardship and show compassion when we can. Justice must be served according to the law. The facts prove this was not an accident. I don't care what the truth is, I just want revenge. Freedom and kindness go hand in hand. """

def classify_sentence(sentence): """Classify sentence into GRT categories based on keyword counts.""" scores = {'good': 0, 'right': 0, 'true': 0} for category, keywords in GRT_KEYWORDS.items(): for word in keywords: if re.search(r'\b' + re.escape(word) + r'\b', sentence, re.IGNORECASE): scores[category] += 1 return scores

def evaluate_text(text): """Evaluate each sentence and return annotated result with color-coded status.""" results = [] sentences = re.split(r'[.?!]', text) for sentence in sentences: sentence = sentence.strip() if not sentence: continue grt_scores = classify_sentence(sentence) active_categories = sum(1 for score in grt_scores.values() if score > 0) status = "PASS" if active_categories >= 2 else "FAIL" max_category = max(grt_scores, key=grt_scores.get) results.append({ 'sentence': sentence, 'category': max_category, 'scores': grt_scores, 'status': status }) return results

=== MAIN ===

for result in evaluate_text(test_text): color = COLOR_GREEN if result['status'] == "PASS" else COLOR_RED print(f"{color}Sentence: {result['sentence']}") print(f"Detected Category: {result['category']}") print(f"Scores: {result['scores']}") print(f"Status: {result['status']}{COLOR_RESET}\n")

GRT means "good, right, true", PLG means "Personal, Local, Global"

Asking someone good with language and Neurolinguistics for insight.

Just want critique. Confirm or disconfirm intentions, for AI to discern


RealVision-ObjectUnderstandingAI: A powerful, real-time object detection and understanding application using Python, OpenCV, and state-of-the-art AI models. Features dual model support (YOLO v8 + MobileNet-SSD), object tracking, performance monitoring, and modern GUI interface. • RealVision-ObjectUnderstandingAI: A powerful, real-time object detection and understanding application using Python, OpenCV, and state-of-the-art AI models. Features dual model support (YOLO v8 + MobileNet-SSD), object tracking, performance monitoring, and modern GUI interface.
RealVision-ObjectUnderstandingAI: A powerful, real-time object detection and understanding application using Python, OpenCV, and state-of-the-art AI models. Features dual model support (YOLO v8 + MobileNet-SSD), object tracking, performance monitoring, and modern GUI interface.
upvotes

/r/PythonCoding monthly "What are you working on?" thread • /r/PythonCoding monthly "What are you working on?" thread

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.


A Small Rust-Backed Utility Library for Python (FastPy-RS, Alpha) • A Small Rust-Backed Utility Library for Python (FastPy-RS, Alpha)

Hello everyone! I come from the Rust ecosystem and have recently started working in Python. I love Rust for its safety and speed, but I fell in love with Python for its simplicity and rapid development. That inspired me to build something useful for the Python community: FastPy-RS, a library of commonly used functions that you can call from Python with Rust-powered implementations under the hood. The goal is to deliver high performance and strong safety guarantees. While many Python libraries use C for speed, that approach can introduce security risks.

Here’s how you can use it:

import fastpy_rs as fr

# Using SHA cryptography
hash_result = fr.crypto.sha256_str("hello")

# Encoding in BASE64
encoded = fr.datatools.base64_encode(b"hello")


# Count word frequencies in a text
text = "Hello hello world! This is a test. Test passed!"
frequencies = fr.ai.token_frequency(text)
print(frequencies)
# Output: {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 2, 'passed': 1}

# JSON parsing
json_data = '{"name": "John", "age": 30, "city": "New York"}'
parsed_json = fr.json.parse_json(json_data)
print(parsed_json)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# JSON serialization
data_to_serialize = {'name': 'John', 'age': 30, 'city': 'New York'}
serialized_json = fr.json.serialize_json(data_to_serialize)
print(serialized_json)
# Output: '{"name": "John", "age": 30, "city": "New York"}'

# HTTP requests
url = "https://api.example.com/data"
response = fr.http.get(url)
print(response)
# Output: b'{"data": "example"}'

I’d love to see your pull requests and feedback! FastPy-RS is open source under the MIT license—let’s make Python faster and safer together. https://github.com/evgenyigumnov/fastpy-rs

By the way, surprisingly, token frequency calculation in FastPy-RS works almost 935 times faster than in regular Python code, so for any text parsing and analysis tasks you will get instant results; at the same time, operations with Base64 and regular expressions also “fly” 6-6.6 times faster thanks to internal optimizations in Rust; the SHA-256 implementation does not lag behind - it uses the same native accelerations as in Python; and the low standard deviation of execution time means that your code will work not only quickly, but also stably, without unexpected “failures”.

P.S. I’m still new to Python, so please don’t judge the library’s minimalism too harshly—it’s in its infancy. If anyone wants to chip in and get some hands-on practice with Rust and Python, I’d be delighted!


Precise screen coordinates for an AI agent • Precise screen coordinates for an AI agent

Hello and thanks for any help in advance! I am working on a project using an AI agent that I have been “training”/feeding info to about windows keybinds and API endpoints for a server I have running on my computer that uses pyautogui to control my computer. My goal is to have the AI agent completely control the UI of my computer. I know this may not be the best way or most efficient way to use an AI agent to do things but it has been a fun project for me to get better at programming. I have gotten pretty far, but I have been stuck with getting my AI agent to click precise areas on the screen. I have tried having it estimate coordinates, I have tried using an image model to crop an area and use opencv and another library I can’t remember the name of right now match that cropped area to a location on the screen, and my most recent attempt has been overlaying a grid when the AI agent uses the screenshot tool to see the screen and having it select a certain box, then specify a region of the box to click in. I have had better luck with my approach using the grid but it is still extremely inconsistent. If anyone has any ideas for how I could transmit precise coordinates from the screen back to the AI agent of places to click would be greatly appreciated.



Built this pytest HTML report tool while going through a rough patch — would love feedback • Built this pytest HTML report tool while going through a rough patch — would love feedback

Pytest-report-plus

I’ve been working on a simple yet extensible Pytest plugin that gives you a clean, clickable, searchable HTML report tool for pytest 🧪📊.

It presently got

✅ Screenshot support ✅ Flaky test badge ✅ Hyperlinking via markers (e.g. JIRA, Testmo) ✅ Search across test names, IDs, and links ✅ Works with or without xdist ✅ Email report support ✅ No DB setup, all local and lightweight

You don't need to write any report generation or merger code at all as it's not just a beautying tool. Whether it's for playwright or for selenium or for unit tests, you can simply use this as long as it's written in pytest framework

It’s been useful in our own CI pipelines and is still evolving. I’d love any feedback!

🛠 Link to the library

And if you find it useful, a ⭐️ would make my day in my that will keep me motivated to push more updates. Contributions are even more welcome.


/r/PythonCoding monthly "What are you working on?" thread • /r/PythonCoding monthly "What are you working on?" thread

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.



May be of interest to anyone looking to learn Python • May be of interest to anyone looking to learn Python
Python for Engineers and Scientists

Hey folks,

I'm opening up my course on Python for Engineers and Scientists for the next week.

I'm migrating from Udemy to my own platform and looking to build some social proof and reviews.

If you do take the course, I'd be super grateful for a review. An email arrives a few days after you enrol with a link to Trustpilot to leave a review.

Here's the link to join: https://www.schoolofsimulation.com/course_python_bootcamp_discounted

Feel free to DM me or share any feedback here too.

Thanks in advance if you do take the course.

Cheers,

Harry

upvotes · comments

/r/PythonCoding monthly "What are you working on?" thread • /r/PythonCoding monthly "What are you working on?" thread

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.


Signal-based State Management in Python: How I Brought Angular's Best Feature to Backend Code • Signal-based State Management in Python: How I Brought Angular's Best Feature to Backend Code

Hey Pythonistas,

I wanted to share a library I've been working on called reaktiv that brings reactive programming to Python with first-class async support. I've noticed there's a misconception that reactive programming is only useful for UI development, but it's actually incredibly powerful for backend systems too.

What is reaktiv?

Reaktiv is a lightweight, zero-dependency library that brings a reactive programming model to Python, inspired by Angular's signals. It provides three core primitives:

  • Signals: Store values that notify dependents when changed

  • Computed Signals: Derive values that automatically update when dependencies change

  • Effects: Execute side effects when signals or computed values change

This isn't just another pub/sub library

A common misconception is that reactive libraries are just fancy pub/sub systems. Here's why reaktiv is fundamentally different:

Pub/Sub Systems Reaktiv
Message delivery between components Automatic state dependency tracking
Point-to-point or broadcast messaging Fine-grained computation graphs
Manual subscription management Automatic dependency detection
Focus on message transport Focus on state derivation
Stateless by design Intentional state management

"But my backend is stateless!"

Even in "stateless" services, ephemeral state exists during request handling:

  • Configuration management

  • Request context propagation

  • In-memory caching

  • Rate limiting and circuit breaking

  • Feature flag evaluation

  • Connection pooling

  • Metrics collection

Real backend use cases I've implemented with reaktiv

1. Intelligent Cache Management

Derived caches that automatically invalidate when source data changes - no more manual cache invalidation logic scattered throughout your codebase.

2. Adaptive Rate Limiting & Circuit Breaking

Dynamic rate limits that adjust based on observed traffic patterns with circuit breakers that automatically open/close based on error rates.

3. Multi-Layer Configuration Management

Configuration from multiple sources (global, service, instance) that automatically merges with the correct precedence throughout your application.

4. Real-Time System Monitoring

A system where metrics flow in, derived health indicators automatically update, and alerting happens without any explicit wiring.

Benefits for backend development

  1. Eliminates manual dependency tracking: No more forgotten update logic when state changes

  2. Prevents state synchronization bugs: Updates happen automatically and consistently

  3. Improves performance: Only affected computations are recalculated

  4. Reduces cognitive load: Declare relationships once, not throughout your codebase

  5. Simplifies testing: Clean separation of state, derivation, and effects

How Dependency Tracking Works

One of reaktiv's most powerful features is automatic dependency tracking. Here's how it works:

1. Automatic Detection: When you access a signal within a computed value or effect, reaktiv automatically registers it as a dependency—no manual subscription needed.

2. Fine-grained Dependency Graph: Reaktiv builds a precise dependency graph during execution, tracking exactly which computations depend on which signals.

# These dependencies are automatically tracked:
total = computed(lambda: price() * (1 + tax_rate()))

3. Surgical Updates: When a signal changes, only the affected parts of your computation graph are recalculated—not everything.

4. Dynamic Dependencies: The dependency graph updates automatically if your data access patterns change based on conditions:

def get_visible_items():
    items = all_items()
    if show_archived():
        return items  # Only depends on all_items
    else:
        return [i for i in items if not i.archived]  # Depends on both signals

5. Batching and Scheduling: Updates can be batched to prevent cascading recalculations, and effects run on the next event loop tick for better performance.

This automatic tracking means you define your data relationships once, declaratively, instead of manually wiring up change handlers throughout your codebase.

Example: Health Monitoring System

from reaktiv import signal, computed, effect

# Core state signals
server_metrics = signal({})  # server_id -> {cpu, memory, disk, last_seen}
alert_thresholds = signal({"cpu": 80, "memory": 90, "disk": 95})
maintenance_mode = signal({})  # server_id -> bool

# Derived state automatically updates when dependencies change
health_status = computed(lambda: {
    server_id: (
        "maintenance" if maintenance_mode().get(server_id, False) else
        "offline" if time.time() - metrics["last_seen"] > 60 else
        "alert" if (
            metrics["cpu"] > alert_thresholds()["cpu"] or
            metrics["memory"] > alert_thresholds()["memory"] or
            metrics["disk"] > alert_thresholds()["disk"]
        ) else 
        "healthy"
    )
    for server_id, metrics in server_metrics().items()
})

# Effect triggers when health status changes
dashboard_effect = effect(lambda: 
    print(f"ALERT: {[s for s, status in health_status().items() if status == 'alert']}")
)

The beauty here is that when any metric comes in, thresholds change, or servers go into maintenance mode, everything updates automatically without manual orchestration.

Should you try it?

If you've ever:

  • Written manual logic to keep derived state in sync

  • Found bugs because a calculation wasn't triggered when source data changed

  • Built complex observer patterns or event systems

  • Struggled with keeping caches fresh

Then reaktiv might make your backend code simpler, more maintainable, and less buggy.

Let me know what you think! Does anyone else use reactive patterns in backend code?

Check it out on GitHub | PyPI