/r/Python
If you have questions or are new to Python use r/LearnPython
News about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
You can find the rules here.
If you are about to ask a "how do I do this in python" question, please try r/learnpython, the Python discord, or the #python IRC channel on Libera.chat.
Please don't use URL shorteners. Reddit filters them out, so your post or comment will be lost.
Posts require flair. Please use the flair selector to choose your topic.
Posting code to this subreddit:
Add 4 extra spaces before each line of code
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
Online Resources
Five life jackets to throw to the new coder (things to do after getting a handle on python)
PyMotW: Python Module of the Week
Online exercices
programming challenges
Asking Questions
Try Python in your browser
Docs
Libraries
Related subreddits
Python jobs
Newsletters
Screencasts
/r/Python
I’m transitioning away from Squarespace to build my photography website due to its limitations (e.g., forcibly downscaling photos, tedious gallery creation, and lack of bulk editing web pages using regex).
Above all, I’d like to automate my workflow of creating web pages containing photos with Python.
1. Create a folder structure for new photo albums on my web server (e.g., /photos/2024/12/02/album-name).
2. Upload web-size and full-resolution images via FTP or similar.
3. Generate HTML for albums using a template (i.e. web previews linking to full-res images).
4. Publish with a simple URL slug (e.g., /20241202-album-name).
I know this can be done with just static HTML web pages in a folder that I can create myself using Python. But mostly I'm looking for advice on a hosting platform or web builder that gives me:
• Access to the file system or API for programmatic uploads.
• The ability to deploy and update HTML/CSS/JS easily.
What hosting service or builder would you recommend that works well with this approach?
budget
parameter. Increasing the budget
parameter increases the predictive power of the algorithm and gives better results on unseen data.PerpetualBooster is a GBM but behaves like AutoML so it is benchmarked also against AutoGluon (v1.2, best quality preset), the current leader in AutoML benchmark. Top 10 datasets with the most number of rows are selected from OpenML datasets. The results are summarized in the following table for regression tasks:
OpenML Task | Perpetual Training Duration | Perpetual Inference Duration | Perpetual RMSE | AutoGluon Training Duration | AutoGluon Inference Duration | AutoGluon RMSE |
---|---|---|---|---|---|---|
Airlines_DepDelay_10M | 518 | 11.3 | 29.0 | 520 | 30.9 | 28.8 |
bates_regr_100 | 3421 | 15.1 | 1.084 | OOM | OOM | OOM |
BNG(libras_move) | 1956 | 4.2 | 2.51 | 1922 | 97.6 | 2.53 |
BNG(satellite_image) | 334 | 1.6 | 0.731 | 337 | 10.0 | 0.721 |
COMET_MC | 44 | 1.0 | 0.0615 | 47 | 5.0 | 0.0662 |
friedman1 | 275 | 4.2 | 1.047 | 278 | 5.1 | 1.487 |
poker | 38 | 0.6 | 0.256 | 41 | 1.2 | 0.722 |
subset_higgs | 868 | 10.6 | 0.420 | 870 | 24.5 | 0.421 |
BNG(autoHorse) | 107 | 1.1 | 19.0 | 107 | 3.2 | 20.5 |
BNG(pbc) | 48 | 0.6 | 836.5 | 51 | 0.2 | 957.1 |
average | 465 | 3.9 | - | 464 | 19.7 | - |
PerpetualBooster outperformed AutoGluon on 8 out of 10 datasets, training equally fast and inferring 5x faster. The results can be reproduced using the automlbenchmark fork here.
What My Project Does
As a Python developer, I’ve always admired the elegance and power of Laravel’s Blade templating engine. Its intuitive syntax, flexible directives, and reusable components make crafting dynamic web pages seamless. Yet, when working on Python projects, I found myself longing for a templating system that offered the same simplicity and versatility. Existing solutions often felt clunky, overly complex, or just didn’t fit the bill for creating dynamic, reusable HTML structures.
That’s when Iris Templates was born—a lightweight, modern Python template engine inspired by Laravel Blade, tailored for Python developers who want speed, flexibility, and an intuitive way to build dynamic HTML.
When developing Python web applications, I noticed a gap in templating solutions:
Iris Templates was created to bridge this gap. It's:
Unlike other Python templating engines:
It’s designed to feel natural and intuitive, reducing the cognitive load of managing templates.
pip install iris-templates
Target Audience
Iris Templates is my way of bringing the elegance of Blade into Python. I hope it makes your projects easier and more enjoyable to develop.
Any advice and suggestions are welcome. There are also examples and unittests in the repository to help you get started!
import random
import time
import sys
import os
def shutdown_system():
"""Simulate a system shutdown."""
print("\nWarning: The PC is about to shut down due to a failed guess!")
time.sleep(2)
print("Shutting down... Please save your work!")
time.sleep(2)
# Simulate shutdown command (but do not actually shut down the PC)
if sys.platform == "win32":
os.system("shutdown /s /f /t 5") # Windows shutdown (comment this line if testing)
elif sys.platform == "darwin" or sys.platform == "linux":
os.system("shutdown -h now") # macOS/Linux shutdown (comment this line if testing)
def number_guessing_game():
"""Number guessing game with a surprise shutdown."""
print("Welcome to the Guess the Number Game!")
print("I have picked a number between 1 and 10.")
# The PC thinks of a random number between 1 and 10
number_to_guess = random.randint(1, 10)
# Set the number of attempts
attempts = 3 # Reduced to 3 attempts for a quicker game
while attempts > 0:
try:
guess = int(input(f"You have {attempts} attempts remaining. Guess the number: "))
# Check if the guess is correct
if guess == number_to_guess:
print("Congratulations! You guessed the number!")
break
else:
print("Incorrect guess. Try again.")
attempts -= 1
except ValueError:
print("Please enter a valid integer.")
# If the player runs out of attempts, trigger a simulated shutdown
if attempts == 0:
print("\nYou failed to guess the number. The game will now end.")
shutdown_system() # Simulate shutdown (not actually remove system)
if __name__ == "__main__":
number_guessing_game()
I recently started experimenting with PyInstaller and PyWebView in conjunction with Django, and I must say, the experience has been incredibly rewarding! i build a django application and after that i use this two libraries together to create a native windows app.
I wrote an post documenting a transition from typical build project tooling using Make and bash scripts, to a Python system. Lots of lessons learned, but it was a very enlightening exercise!
RuleOpt is a Python library that uses optimization-based rule learning for classification tasks, focusing on scalability and model interpretability. It helps practitioners generate transparent, rule-based models, even for large datasets, using linear programming. RuleOpt is designed to integrate smoothly with machine learning pipelines and is especially powerful for extracting rules from ensemble models like random forests and boosting algorithms.
An earlier version of this work is available in our manuscript.
What RuleOpt Does:
Target Audience: This library is ideal for:
Comparison to Existing Alternatives: Here’s how RuleOpt stands out:
Key Features:
Algorithm & Performance: The RuleOpt algorithm focuses on formulating rule extraction as an optimization problem using linear programming. It has been tested on large-scale classification problems and demonstrated scalability and interpretability, even in the case of ensemble models.
Quick Start: Install RuleOpt via pip:
pip install ruleopt
For examples, detailed usage, and API details, check out the documentation.
GitHub Repository:
RuleOpt GitHub
We encourage feedback and contributions! While RuleOpt is a powerful tool, we are continuously working to refine its algorithm and improve usability.
What My Project Does:
ComputeLite is a true serverless tool that leverages the power of WebAssembly (WASM) and SQLite OPFS to ensure that all data and code remain securely in the browser, with no server dependencies or external storage. Right now it supports Python (powered by Pyodide) and SQL( powered by SQLITE)
So you can write all your python code and use Pyodide supported or pure python packages right away in browser without any need to install anything.
Target Audience:
Students, Developers, Could be used for scripting
Comparison:
It can be compared with PyScript but user can create different models which could include scripts with relative imports and packages listed in requirements.txt file
Link: https://computelite.com/
Hi,
I’m writing up an essay about a python program I’ve made for an assessment, which looks at cleaning, reshaping and all that kind of stuff with pandas.
I’m trying to find some good references to back some stuff up, but would like some recommendations!
I already have:
Do you have any others? I’m particularly looking for things that discuss:
Thanks in advance :)
Hello All,
I am currently working on a project where I have to extract data from around 8 different structured templates which together spans 12 Million + pages across 10K PDF Documents.
I am using a mix of Regular Expression and bounding box approach where by 4 of these templates are regular expression friendly and for the rest I am using bounding box to extract the data. On testing the extraction works very well. There are no images or tables, but simple labels and values.
The library that I am currently using is PDF Plumber for data extraction and PyPDF for splitting the documents in small chunks for better memory utilization(PDF Plumber sometimes throws an error when the page count goes above 4000 pages, hence splitting them into smaller chunks temporarily). However this approach is taking 5 seconds per page which is a bit too much considering that I have to process 12M pages.
I did take a look at the different other libraries mentioned in the below link but I am not sure which one to choose as I would love to work with an open source library that is having a good maintenance history and better performance .
https://github.com/py-pdf/benchmarks?tab=readme-ov-file
Request your suggestions . Thanks in advance !
Welcome to our weekly Project Ideas thread! Whether you're a newbie looking for a first project or an expert seeking a new challenge, this is the place for you.
Difficulty: Intermediate
Tech Stack: Python, NLP, Flask/FastAPI/Litestar
Description: Create a chatbot that can answer FAQs for a website.
Resources: Building a Chatbot with Python
Difficulty: Beginner
Tech Stack: HTML, CSS, JavaScript, API
Description: Build a dashboard that displays real-time weather information using a weather API.
Resources: Weather API Tutorial
Difficulty: Beginner
Tech Stack: Python, File I/O
Description: Create a script that organizes files in a directory into sub-folders based on file type.
Resources: Automate the Boring Stuff: Organizing Files
Let's help each other grow. Happy coding! 🌟
Kanban-Tui is a CLI tool that gives you a visual board with moveable tasks in the terminal.
With the newest release v0.4.0, you can create multiple boards with individual columns. More Customization like creating task categories for tasks or change the column visibility is also possible. It also utilizes plotext to give you an overview about several metrics (created/completed/started tasks).
For a quick demo you can use uvx to create a temporary database and config files with: uvx --from kanban-tui ktui demo
They get deleted after you close the application. For detailed instructions and features you can check the Readme on github.
Source Code on github: Link
Terminal affine developers who do not want to miss a nice graphical experience.
Its similar to kanban-python, which I created before before this project but less minimal and the interaction with the tasks is faster more convenient. I.e with the TUI one is able to utilize vim-like motions to move cards around, which comes closer to the feeling of actually moving physical cards.
If you find bugs or are missing a feature, please dont hesitate to open an issue.
demo : https://imgur.com/a/guIH7fM
hey , its my first time posting here.
i got this idea few days ago , i wanted to show the lyrics as status in my discord. so i made it happen!
it tracks your current playing song using spotify api and fetch the lyrics and apply it to rpc.
its really easy to use i hope u enjoy it!
anyone who uses discord and wants a nice RPC.
i couldn't find anything like this in my search so i dont know if there is something similar.
let me know if there is something i can do to make it better!
Hey Pythonistas! 🐍
It's almost that exciting time of the year again! The Advent of Code is just around the corner, and we're inviting everyone to join in the fun!
Advent of Code is an annual online event that runs from December 1st to December 25th. Each day, a new coding challenge is released—two puzzles that are part of a continuing story. It's a fantastic way to improve your coding skills and get into the holiday spirit!
You can read more about it here.
Python is a great choice for these challenges due to its readability and wide range of libraries. Whether you're a beginner or an experienced coder, Python makes solving these puzzles both fun and educational.
2186960-67024e32
We can have up to 200 people in a private leaderboard, so this may go over poorly - but you can join us with the following code: 2186960-67024e32
You can join the Python Discord to discuss the challenges, share your solutions, or you can post in the r/AdventOfCode mega-thread for solutions.
There will be a stickied post for each day's challenge. Please follow their subreddit-specific rules. Also, shroud your solutions in spoiler tags >!like this!<
The Python Discord will also be participating in this year's Advent of Code. Join it to discuss the challenges, share your solutions, and meet other Pythonistas. You will also find they've set up a Discord bot for joining in the fun by linking your AoC account.Check out their Advent of Code FAQ channel.
Let's code, share, and celebrate this festive season with Python and the global coding community! 🌟
Happy coding! 🎄
P.S. - Any issues in this thread? Send us a modmail.
Hey everyone!
Lately, I’ve been spending more time reading code than writing it, but I still code every now and then, mostly in Python. My daily editor — for both coding and just about everything else — has been Emacs for several years now.
Recently, I decided to dig into how the Language Server Protocol (LSP) and Debug Adapter Protocol (DAP) work in Emacs, how they can be integrated, and what minimal configuration is needed to get started. As I explored, I took notes for myself, and eventually, those notes turned into a blog post.
It ended up being quite a long read, but I’m really happy with the result. The more I researched and wrote, the further I drifted from my original goal of creating a quick and minimal Emacs setup guide. I rewrote the introduction a few times before landing on something I felt good about, and now I’m ready to share it with you.
The article isn’t perfect — there are still some rough edges and gaps I plan to address soon. For example:
But it’s in a good enough state to share. If you’re curious and have the patience to read through, I’d love some constructive feedback. Let me know if there’s anything missing that you’d find helpful or if you catch any mistakes I might’ve made.
Here’s the link to the article: https://blog.serghei.pl/posts/emacs-python-ide/
Thanks in advance for your time and thoughts!
Hi everyone, I have been creating and working on a few python projects for fun i have one I'm working on and would love some people to join in and collaborate to make the project better. Many hands make light work and different inputs and ideas can make a project that much better. The GUI is built with ttkbootstrap pretty much a themed fork of tkinter. Would love to see some pull requests in the future and I'm excited to see where this project can go I have created build scripts that basically fit for my environment as they generate RPM packages for installing on Fedora. I do have code in build scripts generate standalone binary files also if needed.
Thanks, find the repo here: https://github.com/BradHeff/Arxis-Pentester
Hello Python community,
My name is Dylan, and I’m a data scientist. I recently developed a fun little project called Kitten Mixer, and I’d love to share it with you and hear your feedback!
Kitten Mixer is a Python-based web app that uses Variational Autoencoders (VAEs) to generate smooth image interpolations of cats. By combining the power of AI with some adorable cat pictures, the app creates unique and visually fascinating blends between different cat images.
Important Note: Don’t forget to press the "English" button on the Kitten Mixer web app and the GitHub repository README to view the content in English!
I’d love to get your thoughts on this project! If you find it interesting or fun, feel free to star the repository on GitHub. I’m also open to suggestions or contributions if anyone wants to collaborate.
Thank you for your time, and I hope you enjoy experimenting with Kitten Mixer!
Pretty Pie Log is a feature-rich Python logging utility designed to improve the readability and usability of logs. It provides customizable colorized output for easy distinction of log levels, supports structured logging with JSON, and offers thread-safe logging for multi-threaded applications. It can be customized with different colors, timezone support, and file logging. It even tracks function execution and provides detailed stack traces for exceptions.
This package is intended for developers working on small—to medium-sized Python applications and those with multi-threaded components. It's ideal for debugging and tracking program behaviour in an organized and visually appealing way. Pretty Pie Log is lightweight enough for scripts but offers features robust enough for small applications or internal tools.
There are several Python logging libraries available, such as logging
. However, Pretty Pie Log stands out because of its:
Other logging libraries might lack one or more of these features, making Pretty Pie Log an ideal choice for developers looking for a lightweight but feature-packed solution.
Check out the full documentation and code on GitHub:
pretty-pie-log GitHub Repository
No more burning through your LLM context window tokens trying to make it understand your codebase.
⭐ Try it out and leave a star: CntxtPY on GitHub
Why try CntxtPY?
Here is my article Multi-Threading in Python and Free threaded Python 3.13 which discuss multi threading in Python and some experiments on free threaded Python 3.13.
https://youtu.be/w3feD6wsDp4?si=hLvDvh4OvSQKf60I
Hello all, I am a final year student who got multiple offers and I have decided to post my interview experiences on youtube. I have also recently attended amazon interview(which I ll be posting soon). I have shared my first interview experience video in the above youtube video. This interview was for Python backend developer role. You can check it out and let me know if I have to change anything from my upcoming videos
Hi everyone. Last time I shared a post about Interface programming using abs in Python, and it got a lot of positive feedback—thank you!
Several people mentioned protocols, so I wrote a new article exploring that topic. In it, I compare protocols with abstract base classes and share my thoughts and experiences with both. You can check it out here: https://www.tk1s.com/python/protocols-vs-abstract-base-classes-in-python Hope you'll like it! Thanks!
Hello /r/Python! It's time to share what you've been working on! Whether it's a work-in-progress, a completed masterpiece, or just a rough idea, let us know what you're up to!
Let's build and grow together! Share your journey and learn from others. Happy coding! 🌟
1. What My Project Does
I created a python package that allows you to generate temporary shareable links to a web-editor for your pandas dataframe!
Running df = pandaBear(df) will generate the free ngrok link from your token in the .env, prompt you for a gmail to authorize access, and then when the person you shared it with finishes editing using the web editor you will have the updated df.
Feel free to check out the demos on GitHub!
2. Target Audience
This is for the scenario where devs are collaborating with nontechnical contributors who want to make quick edits, and the devs want to save time by not having to export the df to a different file and import it again (and deal with whatever issues happen in this formatting and reformatting process).
This is my first python package and it is in the early stages. If people are interested in it I would love to make upgrades to the UI and how it handles large dataframes so please don't hesitate to provide feedback and feature requests!
3. Comparison
There are great, more mature tools like Streamlit for displaying dataframes, but as far as I know, this is the only tool oriented toward temporary sharing and editing.
Here is a link to the project on GitHub (MIT License):
https://github.com/Cyncrovee/CynVee-Hash-Checker_CLI
It's a simple CLI tool to output the hashes of files using multiple algorithms, which at the moment includes:
You simply run the main.py file (with optional arguments) and once you have selected the file you want to use, it will generate the hashes for said file with all the above algorithms (though the README has more detailed intructions).
It's actually a sort of "spin-off" of another project I have in C#, which is a similar thing except with a GUI and less hashing algorithms (with some other differences). I started making it because I just wanted to test out a Neovim config I made, but now I think I may keep using it.
Well to be honest I mostly made it for myself, but I think other people might get some leverage out of it if they need to hash files often. For example, if you're a distro hopper and need to verify lots of ISO files (I've been there lol-)
There are a few similar utilities like certUtil or the checksum package on Chocolatey, however they can be a bit tedious to use in my experience, usually because the commands can get quite long, and/or because it doesn't support the hashing algorithms I need. The downside is that the script can take quite a long time when hashing a large file, so it wouldn’t be the best choice if speed is a concern
I hope you like it! Coming back to Python was nice, the syntax is great and most things just work really easily. Hopefully I can use it for another project soon :]
Okay so I have a python exam in a month and a bit and I need to get good at data wrangling. Looking things up is time consuming. Are there question banks out there or places where I could practice using datasets? Please let me know!
I'm working at small startup, we are using FastAPI, SQLAlchemy, Pydantic, Postgres for backend
I was wondering what practices do people in FAANG use when building production API
Code organization, tests structure, data factories, session managing, error handling, logging etc
I found this repo https://github.com/zhanymkanov/fastapi-best-practices and it gave me some insights but I want more
Please share practices from your company if you think they worth to share
Vectorized programming is really different compared to traditional competitive programming problem that relied on sequential processing. I feel loop and conditional if-else is not really recommended due to performance issue, instead tensor operation can beneficially faster than it.
This makes me wonder if there is such competitive programming platform but for vectorized programming specifically for the NumPy?
In the repository https://github.com/ortolanph/tech-events-europe there is a listing of events for Europe for this year (I know that's only Portugal, but this is what I have done for now). If you want to contribute to next year's event, just follow the rules on the site.
Thanks!
Here is my article on Short-Circuiting in Python . It discusses what is short-circuiting with examples, and also discusses the different advantages of using short-circuiting.