r/Python 1d ago

Daily Thread Sunday Daily Thread: What's everyone working on this week?

9 Upvotes

Weekly Thread: What's Everyone Working On This Week? šŸ› ļø

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!

How it Works:

  1. Show & Tell: Share your current projects, completed works, or future ideas.
  2. Discuss: Get feedback, find collaborators, or just chat about your project.
  3. Inspire: Your project might inspire someone else, just as you might get inspired here.

Guidelines:

  • Feel free to include as many details as you'd like. Code snippets, screenshots, and links are all welcome.
  • Whether it's your job, your hobby, or your passion project, all Python-related work is welcome here.

Example Shares:

  1. Machine Learning Model: Working on a ML model to predict stock prices. Just cracked a 90% accuracy rate!
  2. Web Scraping: Built a script to scrape and analyze news articles. It's helped me understand media bias better.
  3. Automation: Automated my home lighting with Python and Raspberry Pi. My life has never been easier!

Let's build and grow together! Share your journey and learn from others. Happy coding! šŸŒŸ


r/Python 18h ago

Daily Thread Monday Daily Thread: Project ideas!

5 Upvotes

Weekly Thread: Project Ideas šŸ’”

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.

How it Works:

  1. Suggest a Project: Comment your project ideaā€”be it beginner-friendly or advanced.
  2. Build & Share: If you complete a project, reply to the original comment, share your experience, and attach your source code.
  3. Explore: Looking for ideas? Check out Al Sweigart's "The Big Book of Small Python Projects" for inspiration.

Guidelines:

  • Clearly state the difficulty level.
  • Provide a brief description and, if possible, outline the tech stack.
  • Feel free to link to tutorials or resources that might help.

Example Submissions:

Project Idea: Chatbot

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

Project Idea: Weather Dashboard

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

Project Idea: File Organizer

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! šŸŒŸ


r/Python 4h ago

Showcase My first python package got 844 downloads šŸ˜­šŸ˜­

115 Upvotes

I know 844 downloads aint much, but i feel so proud.

This was my first project that i published.

Here is the package link:Ā https://pypi.org/project/Font/

Source code:Ā https://github.com/ivanrj7j/Font

What My Project Does

My project is a library for rendering custom font using opencv.

Target Audience

  • Computer vision devs
  • People who are working with text and images etc

ComparisonĀ 

From what ive seen there arent many other projects out there that does this, but some of similar projects i have seen are:


r/Python 3h ago

Discussion Which libraries have the best docs?

21 Upvotes

Hi,

Out of all the available python libraries and frameworks, which ones do you think have the best documentation?

I am looking for examples to learn how to create good docs for a project I am working on.

Thanks!


r/Python 4h ago

Discussion Python 3.12 vs Python 3.13 ā€“ performance testing

16 Upvotes

This article describes the performance testing results of Python 3.13 compared to Python 3.12. A total of 100 various benchmark tests were conducted on computers with the AMD Ryzen 7000 series and the 13th-generation of Intel Core processors for desktops, laptops or mini PCs.

https://en.lewoniewski.info/2024/python-3-12-vs-python-3-13-performance-testing/


r/Python 1h ago

Tutorial Build an intuitive CLI app with Python argparse

ā€¢ Upvotes

A while ago, I used Python and the argparse library to build an app for managing my own mail server. That's when I realized that argparse is not only flexible and powerful, but also easy to use.

I always reach for argparse when I need to build a CLI tool because it's also included in the standard library.

I'll show you how to build a CLI tool that mimics the docker command because I find the interface intuitive and would like to show you how to replicate the same user experience with argparse. I won't be implementing the behavior but you'll be able to see how you can use argparse to build any kind of easy to use CLI app.

See a real example of such a tool in this file.

Docker commands

I would like the CLI to provide commands such as:

  • docker container ls
  • docker container start
  • docker volume ls
  • docker volume rm
  • docker network ls
  • docker network create

Notice how the commands are grouped into seperate categories. In the example above, we have container, volume, and network. Docker ships with many more categories. Type docker --help in your terminal to see all of them.

Type docker container --help to see subcommands that the container group accepts. docker container ls is such a sub command. Type docker container ls --help to see flags that the ls sub command accepts.

The docker CLI tool is so intuitive to use because you can easily find any command for performing a task thanks to this kind of grouping. By relying on the built-in --help flag, you don't even need to read the documentation.

Let's build a CLI similar to the docker CLI tool command above.

I'm assuming you already read the argparse tutorial

Subparsers and handlers

I use a specific pattern to build this kind of tool where I have a bunch of subparsers and a handler for each. Let's build the docker container create command to get a better idea. According to the docs, the command syntax is docker container create [OPTIONS] IMAGE [COMMAND] [ARG...].

```python from argparse import ArgumentParser

def add_container_parser(parent): parser = parent.add_parser("container", help="Commands to deal with containers.") parser.set_defaults(handler=container_parser.print_help)

def main(): parser = ArgumentParser(description="A clone of the docker command.") subparsers = parser.add_subparsers()

add_container_parser(subparsers)

args = parser.parse_args()

if getattr(args, "handler", None): args.handler() else: parser.print_help()

if name == "main": main() ```

Here, I'm creating a main parser, then adding subparsers to it. The first subparser is called container. Type python app.py container and you'll see a help messaged printed out. That's because of the set_default method. I'm using it to set an attribute called handler to the object that will be returned after argparse parses the container argument. I'm calling it handler here but you can call it anything you want because it's not part of the argparse library.

Next, I want the container command to accept a create command:

```python ... def add_container_create_parser(parent): parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=parser.print_help)

def add_container_parser(parent): parser = parser.add_parser("container", help="Commands to deal with containers.") parser.set_defaults(handler=container_parser.print_help)

subparsers = parser.add_subparsers()

add_container_create_parser(subparsers) ... ```

Type python app.py container create to see a help message printed again. You can continue iterating on this pattern to add as many sub commands as you need.

The create command accepts a number of flags. In the documentation, they're called options. The docker CLI help page shows them as [OPTIONS]. With argparse, we're simply going to add them as optional arguments. Add the -a or --attach flag like so:

```python ... def add_container_create_parser(parent): parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=parser.print_help)

parser.add_argument("-a", "--attach", action="store_true", default=False, help="Attach to STDIN, STDOUT or STDERR") ... ```

Type python app.py container create again and you'll see that it contains help for the -a flag. I'm not going to add all flags, so next, add the [IMAGE] positional argument.

```python ... def add_container_create_parser(parent): parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=parser.print_help)

parser.add_argument("-a", "--attach", action="store_true", default=False, help="Attach to STDIN, STDOUT or STDERR") parser.add_argument("image", metavar="[IMAGE]", help="Name of the image to use for creating this container.") ... ```

The help page will now container information about the [IMAGE] command. Next, the user can specify a command that the container will execute on boot. They can also supply extra arguments that will be passed to this command.

```python from argparse import REMAINDER

... def add_container_create_parser(parent): parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=parser.print_help)

parser.add_argument("-a", "--attach", action="store_true", default=False, help="Attach to STDIN, STDOUT or STDERR") parser.add_argument("image", metavar="IMAGE [COMMAND] [ARG...]", help="Name of the image to use for creating this container. Optionall supply a command to run by default and any argumentsd the command must receive.") ... ```

What about the default command and arguments that the user can pass to the container when it starts? Recall that we used the parse_args method in our main function:

python def main(): ... args = parser.parse_args() ...

Change it to use parse_known_args instead:

```python def main(): parser = ArgumentParser(description="A clone of the docker command.") subparsers = parser.add_subparsers()

add_container_parser(subparsers)

known_args, remaining_args = parser.parse_known_args()

if getattr(known_args, "handler", None): known_args.handler() else: parser.print_help() ```

This will allow argparse to capture any arguments that aren't for our main CLI in a list (called remaining_args here) that we can use to pass them along when the user executes the container create animage command.

Now that we have the interface ready, it's time to build the actual behavior in the form of a handler.

Handling commands

Like I said, I won't be implementing behavior but I still want you to see how to do it.

Earlier, you used set_defaults in your add_container_create_parser function:

python parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=parser.print_help) ...

Instead of printing help, you will call another function called a handler. Create the handler now:

python def handle_container_create(args): known_args, remaining_args = args print( f"Created container. image={known_args.image} command_and_args={' '.join(remaining_args) if len(remaining_args) > 0 else 'None'}" )

It will simply print the arguments and pretend that a container was created. Next, change the call to set_defaults:

python parser = parent.add_parser("create", help="Create a container without starting it.") parser.set_defaults(handler=handle_container_create, handler_args=True) ...

Notice that I'm also passing a handler_args argument. That's because I want my main function to know whether the handler needs access to the command line arguments or not. In this case, it does. Change main to be as follows now:

```python def main(): parser = ArgumentParser(description="A clone of the docker command.") subparsers = parser.add_subparsers()

add_container_parser(subparsers)

known_args, remaining_args = parser.parse_known_args()

if getattr(known_args, "handler", None):
    if getattr(known_args, "handler_args", None):
        known_args.handler((known_args, remaining_args))
    else:
        known_args.handler()
else:
    parser.print_help()

```

Notice that I added the following:

python ... if getattr(known_args, "handler_args", None): known_args.handler((known_args, remaining_args)) else: known_args.handler()

If handler_args is True, I'll call the handler and pass all arguments to it.

Use the command now and you'll see that everything works as expected:

```shell python app.py container create myimage

Created container. image=myimage command_and_args=None

python app.py container create myimage bash

Created container. image=myimage command_and_args=bash

python app.py container create myimage bash -c

Created container. image=myimage command_and_args=bash -c

```

When implementing real behavior, you'll simply use the arguments in your logic.

Now that you implemented the container create command, let's implement another one under the same category - docker container stop.

Add a second command

Add the following parser and handler:

```python def handle_container_stop(args): known_args = args[0] print(f"Stopped containers {' '.join(known_args.containers)}")

def add_container_stop_parser(parent): parser = parent.add_parser("stop", help="Stop containers.") parser.add_argument("containers", nargs="+")

parser.add_argument("-f", "--force", help="Force the containers to stop.")
parser.set_defaults(handler=handle_container_stop, handler_args=True)

```

Update your add_container_parser function to use this parser:

```python def add_container_parser(parent): parser = parent.add_parser("container", help="Commands to deal with containers.") parser.set_defaults(handler=parser.print_help)

subparsers = parser.add_subparsers()

add_container_create_parser(subparsers)
add_container_stop_parser(subparsers)

```

Use the command now:

```shell python app.py container stop abcd def ijkl

Stopped containers abcd def ijkl

```

Perfect! Now let's create another category - docker volume

Create another category

Repeat the same step as above to create as many categories as you want:

python def add_volume_parser(parent): parser = parent.add_parser("volume", help="Commands for handling volumes") parser.set_defaults(handler=parser.print_help)

Let's implement the ls command like in docker volume ls:

```python def volume_ls_handler(): print("Volumes available:\n1. vol1\n2. vol2")

def add_volume_ls_parser(parent): parser = parent.add_parser("ls", help="List volumes") parser.set_defaults(handler=volume_ls_handler)

def add_volume_parser(parent): ... subparsers = parser.add_subparsers() add_volume_ls_parser(subparsers) ```

Notice how I'm not passing any arguments to the volume_ls_handler, thus not adding the handler_args option. Try it out now:

```shell python app.py volume ls

Volumes available:

1. vol1

2. vol2

```

Excellent, everything works as expected.

As you can see, building user friendly CLIs is simply with argparse. All you have to do is create nested subparsers for any commands that will need their own arguments and options. Some commands like docker container create are more involved than docker volume ls because they accept their own arguments but everything can be implemented using argparse without having to bring in any external library.

Here's a full example of what we implemented so far:

```python from argparse import ArgumentParser

def handle_container_create(args): known_args, remaining_args = args print( f"Created container. image={known_args.image} command_and_args={' '.join(remaining_args) if len(remaining_args) > 0 else 'None'}" )

def add_container_create_parser(parent): parser = parent.add_parser("create", help="Create a container without starting it.")

parser.add_argument(
    "-a",
    "--attach",
    action="store_true",
    default=False,
    help="Attach to STDIN, STDOUT or STDERR",
)
parser.add_argument(
    "image",
    metavar="IMAGE",
    help="Name of the image to use for creating this container.",
)
parser.add_argument(
    "--image-command", help="The command to run when the container boots up."
)
parser.add_argument(
    "--image-command-args",
    help="Arguments passed to the image's default command.",
    nargs="*",
)

parser.set_defaults(handler=handle_container_create, handler_args=True)

def handle_container_stop(args): known_args = args[0] print(f"Stopped containers {' '.join(known_args.containers)}")

def add_container_stop_parser(parent): parser = parent.add_parser("stop", help="Stop containers.") parser.add_argument("containers", nargs="+")

parser.add_argument("-f", "--force", help="Force the containers to stop.")
parser.set_defaults(handler=handle_container_stop, handler_args=True)

def add_container_parser(parent): parser = parent.add_parser("container", help="Commands to deal with containers.") parser.set_defaults(handler=parser.print_help)

subparsers = parser.add_subparsers()

add_container_create_parser(subparsers)
add_container_stop_parser(subparsers)

def volume_ls_handler(): print("Volumes available:\n1. vol1\n2. vol2")

def add_volume_ls_parser(parent): parser = parent.add_parser("ls", help="List volumes") parser.set_defaults(handler=volume_ls_handler)

def add_volume_parser(parent): parser = parent.add_parser("volume", help="Commands for handling volumes") parser.set_defaults(handler=parser.print_help)

subparsers = parser.add_subparsers()
add_volume_ls_parser(subparsers)

def main(): parser = ArgumentParser(description="A clone of the docker command.") subparsers = parser.add_subparsers()

add_container_parser(subparsers)
add_volume_parser(subparsers)

known_args, remaining_args = parser.parse_known_args()

if getattr(known_args, "handler", None):
    if getattr(known_args, "handler_args", None):
        known_args.handler((known_args, remaining_args))
    else:
        known_args.handler()
else:
    parser.print_help()

if name == "main": main() ```

Continue to play around with this and you'll be amazed at how powerful argparse is.


I originally posted this on my blog. Visit me if you're interested in similar topics.


r/Python 54m ago

News Teaching the world's largest programming lesson

ā€¢ Upvotes

This past Saturday I taught the world's largest programming lesson, with 1668 students, breaking the previous record of 724 students.

We broke the record in Portugal šŸ‡µšŸ‡¹ and the event was co-organised by a local university and a company I used to work at.

It was an insane event. I have been in plenty of events with WAY more than 2k people. Music festivals, sports matches, etc. And yet, nothing beat being on stage, teaching Python to ~1750 students. (The official record is at 1668 because some students were disqualified for not actually following the lesson šŸ¤¦.)

The lesson was split in three and I taught the middle segment, which was scheduled to last for half of the lesson.

The professor before me taught the students what an algorithm was, conceptually. One of the examples provided was a brute forcy algorithm to solve a Sudoku puzzle.

Then, I taught them some basic Python syntax. The objective was for me to introduce enough syntax so that we could implement the algorithm described in the first part on top of an abstraction that I created beforehand.

Finally, a third professor showed a couple of more advanced applications of Python, like creating a RAG application to interact with a major literary work that Portuguese students are supposed to read in school.

If you want to know more details about what I actually taught / did with Sudoku, you can take a look at this blog article of mine: https://mathspp.com/blog/teaching-the-worlds-largest-programming-lesson Otherwise, I'm just ecstatic that I got to be a part of this and since I don't think it's reasonable to go out on the streets and scream all of this, I decided to post it here.

Please, rejoice with me! šŸš€


r/Python 8h ago

Tutorial How to benchmark with pytest-benchmark

12 Upvotes

I wrote a tutorial that walks you through how to benchmark Python code using pytest-benchmark. It starts out with a basic example and then evolves things as new requirements are added to the software. SPOILER ALERT: There's a performance regression.

https://bencher.dev/learn/benchmarking/python/pytest-benchmark/


r/Python 9h ago

Discussion Reading CAN Bus signals from and mf4 file.

5 Upvotes

Anybody know how I can read CAN Bus signals from an MF4 file. Any libraries for it, or if I need to convert the file into another format?


r/Python 4h ago

Showcase Flexible Array Operations / Urluna

1 Upvotes

I'm excited to share my new library, Urluna. I made it with pure Python. Please take a look and made a feedback!

What My Project does?

Urluna is a Python library provide methods for performing various array and matrix operations.

It is the Math library for matrices, It is simple like Numpy, also speed is the same. It can be used for data analyzing, for school, for science and for random list number!

In the future I am planning improve this project with CUDA.

In the repo I explained all methods with a simple documentationĀ https://github.com/bursow/urluna

pypi :

https://pypi.org/project/urluna/1.6/

Happy coding!


r/Python 19h ago

Showcase Old school 2000s mouse accessory: Particles following your mouse! Get color under cursor! And more!

15 Upvotes

I would have loved to instead call this thread: "You can now have shit stuck to your mouse", but I felt it wouldn't take very long until it was removed.

What my project does:

I've had an idea somewhere in 2022: I want rainbow trails for my mouse cursor. Available software was naught. So I made it myself!
- It can draw particles of any number and color spawning from your mouse cursor. With multiple vectors, influences from mouse motion and rotation, many ideas can be realized: Crazy or decent, river or beehive, smoke or explosion.
- or it can be the time
- Get RGB or RGB complementary color
- or get RYB and RYB complementary color from under it.
- Also useless stuff like the time with milliseconds, system cpu and ram usage, individual or at the same time, if you need it visible there for some obscure reason.
- An image is also possible - default is the poop emoji, of course.

(Just got a new idea: get color from under cursor and spawn particle with it for a sort of "scraping off pixels" effect)

The function to have a little square with the color under the cursor is sometimes extremely helpful, so I put some work into it and that's why there's a RYB version of it.

I know my GUI is horribly complicated, maybe even extremely so. I don't know how I can have this much customizability in any reasonable format. I'd love for it to look better - maybe move explanations to hover-text. But I'd need to swutch to raw tKinter or Qt for that. And since PySimpleGUI has me puking into his inbox every 365 days, I just switched to FreeSimpleGUI which is a free fork of an earlier version that still HAS gpl license or something like that.
Or maybe have an easier view and them this as advanced options.

Today I finished another round of updates and fixes - which I seemingly tend to do every 6 month or so. I am OK enough with it to show you :) I even made an executable for those who don't want to install Python. Because 3.11+, I think, is necessary. I always update to the newest version. I don't understand why people still program new stuff with 2.7, or what it was.

I'm still considering trying to figure out spacial hashes and pygame time dilation in order to improve the backend further. But, luckily, I'm currently too stupid to do so. :D

Here's a link to my repo:
https://github.com/LtqxWYEG/ShitStuckToYourMouse

Please tell me if the executable doesn't work on your PC (only tested on mine) or if there are any other issues. :)

Target audience:

Anyone who wants to be particularly productive while working. Hehe!

Comparison:

None that I could find. Maybe some programs that are actually from the 90s / early 2000s still exist. Who knows?


r/Python 4h ago

Showcase Emmett55 is now available

1 Upvotes

In the same month of Emmett's 10th anniversary, I also published Emmett55: the micro web framework for inventors.

Emmett55 takes advantage of some of the unique features of Emmett, like the RSGI protocol, the Rust powered router, or the Pipeline, but with an overall smaller set of features and fewer dependencies.

Emmett55's primary target audience consists of those projects which won't need the fullstack-like set of features of Emmett, or for those who prefer a different set of libraries like SQLAlchemy for the database layer or Jinja for the templates.

Check it out at https://github.com/emmett-framework/emmett55


r/Python 23h ago

Showcase I made a website for finding deals on Pokemon cards on Ebay

29 Upvotes

Site: https://www.jimmyrustles.com/pokemondeals

Github: https://www.github.com/sgriffin53/pokemon_tcg_deal_finder_app

What My Project Does

For the past few weeks I've been working on a Pokemon deal finder website. It works by finding listings from Ebay and card valuations from Pricecharting then returns the listings with the biggest difference in card price compared to card valuation.

It searches Ebay for 112 different sets and right now it has around 200,000 listings.

The listings will be updated every 8 hours.

It seems pretty successful at identifying cards. Most of the misidentification seems to be when a seller has mislabelled the card or set in the title, but for the most part, it seems good at identifying the cards.

It seems to find deals well, though a lot of the deals are heavily played cards that are underpriced due to their condition. For example, on the front page, there's a heavily played Umbreon EX #112 from Unseen Forces that's valued at $165.60 and the price is $19.96.

Target Audience

There's a large market for people buying and selling cards on Ebay. Users are constantly looking for good deals, and this tool is a way to automate looking for deals by comparing listing prices to valuations.

Comparison

There was a site a while ago that I believe did the same thing, but it shut down. There are other pokemon deal sites but they seem to be manually curated rather than done automatically. I think this could be a unique and useful tool.

Let me know what you think.


r/Python 1d ago

Tutorial I shared a 1+ Hour Streamlit Course on YouTube - Learn to Create Python Data/Web Apps Easily

52 Upvotes

Hello, I just shared a Python Streamlit Course on YouTube. Streamlit is a Python framework for creating Data/Web Apps with a few lines of Python code. I covered a wide range of topics, started to the course with installation and finished with creating machine learning web apps. I am leaving the link below, have a great day!

https://www.youtube.com/watch?v=Y6VdvNdNHqo&list=PLTsu3dft3CWiow7L7WrCd27ohlra_5PGH&index=10


r/Python 23h ago

Showcase Accounting (book-keeping) rules for chart of accounts and ledger implemented in Python

26 Upvotes

Target audience

I think ther is a big void between people who code and who know accounting that is filled with expensive software. Hope this demo can show that if there where common open data formats for charts of accounts, the cost of accounting software could be much lower.

What this project does

I was working for a while on implementing accounting rules in Python and came up with quite a minimal ledger that allows to create your own chart of accounts, post double and multiple entries and close the ledger properly at accounting period end. The workflow is based on just three classes - `Chart`, `Book` and `Entry` and results in `TrialBalance`, `BalanceSheet` and `IncomeStatement`. The code in under 600 lines, but many things are realistic, for example there are contra accounts, accounts do not go negative, there are both double and multiple entries, and at period end the chart informs which accounts should close to retained earnings. Everything saves to JSON files.

I previously had a CLI for similar project but now it is just one module. The code is covered with tests, mypy and ruff checks that are invoked through `just` command runner.

The project is available at https://github.com/epogrebnyak/abacus-minimal/

Comparison

I think hledger, medici and microbooks API are the closest alternatives.


r/Python 22h ago

Showcase Xenharmlib 0.2.0 released - Advanced music theory library

13 Upvotes

Hi everyone,

Last week I released version 0.2.0 of xenharmlib. New features focus mostly on post-tonal theory and scale transformations. You can get a good overview on "What's new in 0.2.0".

(Source codeĀ here)

I'm still looking for contributors. So if you are interested, shoot me a message.

What My Project Does

(taken from the docs) Xenharmlib is a music theory library for the exploration and research of microtonality, diatonic set theory, non-standard notations, and many more. The library implements a superset of Western classical music theory, so you can also use it to compose and analyze music in the boundaries of the common practice period or 20th century Western music.

Target Audience

Composers who want to get answers to theoretical questions pertaining to structures of musical scales, note intervals, frequencies and frequency ratios in equal division tunings. People who want to explore microtonality or non-western musical theory in general.

Comparison

*Ā mingusĀ Everything in mingus can also be done in xenharmlib
*Ā pytuningĀ supports slightly more tuning methods and export formats, however does not support microtonal notation, note / interval calculation or post-tonal scale transformations.
*Ā music21Ā is much more mature in providing an analytical toolset, however supports only traditional western equal temperament


r/Python 1d ago

Showcase Environments Utils - Detect Your (quirky) Python Runtime Environment

39 Upvotes

Hey, r/Python!

What My Project Does:

Over the years, Iā€™ve been working on a Python package called Environments Utils that helps detect characteristics of the environments where your Python script is running. Itā€™s built to handle various edge cases and odd environments Iā€™ve encountered. For example, it can determine if your script runs inside a Jupyter Notebook, on a SLURM cluster, or within Rosetta on macOS. The package also identifies system architecture, operating system, GPU availability, and even whether you have an internet connection - all with no additional dependencies!

Target Audience:

This package is designed for developers and data scientists who work in diverse environments, such as cloud platforms and high-performance computing clusters. I find it particularly useful when I need to adapt a pipeline depending on which system it is being installed on.

  • Production Use: You can use the package to adapt your script's behaviour based on the runtime environment (e.g., using different logging mechanisms in a SLURM cluster).
  • Development/Debugging: If you're writing code that needs to adapt to odd environments like Colab, TMUX, or hybrids like macOS Rosetta, this package can save you some headaches. I had several scripts that only broke down in COLAB or Rosetta etc, and this made the error messages that users reported back to me much more informative.

Installation:

As usual, it's just a pip install away:

pip install environments_utils

Examples:

Detect Rosetta on macOS:

from environments_utils import is_macos_rosetta

if is_macos_rosetta():
    print("I am running inside Rosetta!")

Detect SLURM node:

from environments_utils import is_slurm_node

if is_slurm_node():
    print("Running on a SLURM node!")

GitHub: LucaCappelletti94/environments_utils

Happy to hear your thoughts, feedback, or ideas for new features!


r/Python 1d ago

Discussion Udemy 100 days of code

7 Upvotes

For anyone else who has worked through this course- how difficult were days 39 and 40? I understand how to use requests and how to use API calls (for reference, days 39 and 40 were the airline price finder days), but I just canā€™t wrap my head around this. Iā€™m probably just going to skip this one lol.


r/Python 1d ago

Discussion I'm making a periodic table on python.

35 Upvotes

I'm making a periodic table that has almost everything that a element can have. I made a Github repository, so check it out! Also, the "discussion" flair is because I know that the code is pretty bad, so if anybody has anything to add (both for the table and for the code ), please tell me!

Github link: https://github.com/Mountainkaio/Python-s-periodic-table


r/Python 2d ago

Discussion I Understand Machine Learning with Numpy and PyTorch Better Since I Started Focusing on the Basics

113 Upvotes

I've recently started appreciating ML in Python more since I began looking at the concepts from the ground up.

For example, I took a closer look at the basics of classification neural networks, and now I have a better understanding of how more complex networks work. The foundation here is logistic regression, and understanding that has really helped me grasp the overall concepts better. It also helped me implementing the code in Numpy and in PyTorch.

If you're also interested in Machine Learning with Python and sometimes feel overwhelmed by all the complicated topics, I really recommend going back to the basics. I've made a video where I explain logistic regression step by step using a simple example.

The video will be attached here: https://youtu.be/EB4pqThgats?si=Z-lXOjuNKEP5Yehn

I'd be happy if you could take a look and give me some feedback! I'm curious to hear what you think of my approach and if you have any tips on how to make it even clearer.


r/Python 2d ago

Showcase Pyloid: A Web-Based GUI Library for Desktop Applications - v0.11.0 Released

61 Upvotes

šŸŒ€ What is Pyloid?

Pyloid is the Python backend version of Electron, Tauri, designed to simplify desktop application development. This open-source project, built on QtWebEngine and PySide6, provides seamless integration with various Python features, making it easy to build powerful applications effortlessly.

šŸš€ Why Pyloid?

With Pyloid, you can leverage the full power of Python in your desktop applications. Its simplicity and flexibility make it the perfect choice for both beginners and experienced developers looking for a Python-focused alternative to Electron or Tauri. It is especially optimized for building AI-powered desktop applications.

GitHub:Ā Pyloid GitHub
Docs:Ā Pyloid Docs

šŸŽÆ Target Audience

Pyloid is designed for a wide range of developers, particularly those who:

  • Python Developers: If you are familiar with Python and want to build desktop applications, Pyloid provides a smooth transition to desktop development without needing to learn new languages like Rust or C++.
  • AI and Machine Learning Enthusiasts: Pyloid is optimized for AI-powered desktop applications, making it an ideal tool for developers who want to integrate machine learning models or AI features directly into their apps.
  • Web Developers: Developers who are proficient in web technologies (HTML, CSS, JavaScript) and want to bring their skills into desktop app development will find Pyloid's web-based GUI support particularly useful.
  • Cross-Platform App Developers: Pyloid allows you to build applications that run seamlessly across multiple operating systems (Windows, macOS, Linux), making it a great choice for developers looking to target different platforms with a single codebase.
  • Electron/Tauri Users Seeking Python Integration: If you're familiar with Electron or Tauri and are looking for a Python-focused alternative with a similar development experience, Pyloid offers the same advantages but with deeper Python integration.

Pyloid v0.11.0 Release Notes

Weā€™re excited to announce the release of Pyloid version 0.11.0! This update brings several major improvements and new features to enhance both functionality and usability. Hereā€™s a breakdown of the key changes:

  1. Renaming & Optimization: The project has been officially renamed from Pylon to Pyloid, along with a series of optimizations to improve performance.
  2. Documentation Overhaul: All official documentation has been thoroughly updated and reorganized to reflect the new name and the latest features, ensuring a smoother experience for developers.
  3. Dynamic Tray & Icon Updates: Tray and icon-related methods now support dynamic updates, meaning changes can be applied even after the application is running.
  4. Enhanced Tray Features: New tray tooltip options and tray icon animations have been added for better customization and visual feedback.
  5. Advanced Timer Functionality: Several new timer features have been introduced, including:
    • High-precision timers
    • Single-shot timers
    • Periodic timers
  6. File Watcher Functionality: A new file watcher feature is now available, enabling monitoring of file or directory changes with the ability to trigger callback functions.
  7. Notification Click Callbacks: You can now define callback functions to handle click events on notifications, providing more interactive and responsive notifications.
  8. Comprehensive Guides: The official documentation now includes detailed guides to help users get the most out of these new features.

šŸ” Comparison with Existing Alternatives

PyWebview vs Pyloid Comparison

1. Core Architecture

  • PyWebview: PyWebview is a lightweight wrapper around native web engines (e.g., WebKit on macOS and Linux, MSHTML on Windows) that allows you to easily create web-based GUIs using Python. It integrates well with Python code, making it easy to build desktop applications with HTML, CSS, and JavaScript.
  • Pyloid: Pyloid is built on QtWebEngine and PySide6, offering a more powerful framework that can handle complex applications. It is optimized for developing desktop applications with Python, particularly those involving AI integration.

Key Difference: PyWebview relies on native web engines to support simple applications, while Pyloid uses QtWebEngine to provide a more flexible and scalable environment.

2. Python and JavaScript Integration

  • PyWebview: PyWebview focuses on executing JavaScript from Python and handling communication between the two. However, developers often need to write JavaScript inside Python strings, which can limit IDE support and make debugging more challenging.
  • Pyloid: Pyloid provides a Bridge API for smooth communication between Python and JavaScript. This API offers more flexibility and allows easy integration of Python functionality with web-based frontends.

Key Difference: Pyloid offers a more intuitive and developer-friendly integration for Python-JS interactions, whereas PyWebview is more limited in this aspect.

3. Frontend Framework Integration

  • PyWebview: PyWebview provides limited integration with modern frontend frameworks like React and Vue. While these frameworks can be used, PyWebview primarily focuses on HTML, CSS, and JavaScript, and integrating other frameworks can be more complex.
  • Pyloid: Pyloid offers templates that make it easy to integrate modern frontend libraries and frameworks like React, providing a more flexible approach to frontend development.

Key Difference: Pyloid is better suited for integrating modern frontend libraries, while PyWebview has more limitations in this area.

4. Use Cases and Target Applications

  • PyWebview: PyWebview is ideal for quickly developing simple desktop applications. Itā€™s particularly useful for lightweight applications that need to combine Python with a web-based GUI.
  • Pyloid: Pyloid is designed for building complex, feature-rich desktop applications that integrate AI or machine learning, making it suitable for larger projects.

Key Difference: PyWebview is best for simpler applications, while Pyloid is better suited for complex projects with AI integration.

5. System Tray and Multi-Window Support

  • PyWebview: PyWebview does not natively support system tray icons and has limited multi-window management capabilities.
  • Pyloid: Pyloid includes system tray support and robust multi-window management, allowing developers to easily create and manage multiple windows and implement complex UIs.

Key Difference: Pyloid offers more desktop-specific features such as system tray icons and multi-window management, which PyWebview lacks.

6. Desktop-Specific Features

  • PyWebview: PyWebview focuses on embedding web content and connecting it with Python logic but does not offer extensive desktop-specific features such as clipboard management, notifications, or desktop capture.
  • Pyloid: Pyloid provides desktop-specific features such as clipboard access, notifications, monitor management, desktop capture, file watchers, dynamic tray icons, and more, giving developers more control over desktop application functionality.

Key Difference: Pyloid offers a richer set of desktop application features compared to PyWebview.

7. Cross-Platform Support

  • PyWebview: PyWebview works on Windows, macOS, and Linux but relies on the native web engines of each platform, which can result in inconsistent behavior across different systems.
  • Pyloid: Pyloid uses QtWebEngine, ensuring more consistent performance and behavior across Windows, macOS, and Linux.

Key Difference: Pyloid provides more reliable cross-platform support due to QtWebEngine, while PyWebviewā€™s reliance on native web engines can lead to inconsistencies.

8. Ease of Use

  • PyWebview: PyWebview is very lightweight and easy to use, making it an excellent choice for small projects or prototypes. Its simplicity is its strength, but it can be limiting for more complex applications.
  • Pyloid: Pyloid is slightly more complex due to its additional functionality but offers a much richer development experience for larger projects and more demanding applications.

Key Difference: PyWebview is simpler and better suited for small apps, while Pyloid, with its broader feature set, is ideal for complex apps.

Conclusion:

  • PyWebview is a great tool for quickly and easily developing lightweight applications that combine Python and web technologies.
  • Pyloid is optimized for AI-powered, scalable cross-platform desktop applications, offering more features and flexibility for larger, more complex projects.

If youā€™re looking to build a simple desktop app, PyWebview may be the better option, but if you need to develop an AI-based or more scalable project, Pyloid is the superior choice.


r/Python 3d ago

Showcase Pyinstrument v5.0 - flamegraphs for Python!

110 Upvotes

Hi reddit! I've been hard at work on a new pyinstrument feature that I'm really excited to show off. It's a completely new HTML renderer that lets you see visually exactly what happened as the program was running.

What it does First, some context: Pyinstrument is a statistical profiler for Python. That means you can activate it when you're running your code, and pyinstrument will record what happens periodically, and at the end, give you a report that tells you where the time was spent.

Target Audience Anyone wondering if their Python program could be faster! Not only is it useful from a performance perspective, it's also a nice way to understand what's going on when a program runs.

Comparison If you've used profilers like cProfile before, pyinstrument aims to be a more user-friendly, intuitive alternative to that. It's also a statistical profiler, it only samples your program periodically, so it shouldn't slow the program down too much.

So, what's new? Up until now, the output has been some form of call stack. That's great to identify the parts of code that are taking the most time. But it can leave some information missing - what's the pattern of the code execution? What order do things happen in? When do the slow functions get called?

https://joerick.s3.amazonaws.com/pyi+video+1.gif

That's where the new HTML mode comes in! Run pyinstrument with the -r html flag, and when the browser opens up you can see the option to view as a Timeline. From there, you can see the big picture, and then zoom in all the way to milliseconds to see what your program is up to!

More info in the writeup on my blog.

Give it a try on your codebase! Just do pip install -U pyinstrument to get the latest version and use the -r html flag to use the new mode.


r/Python 2d ago

Daily Thread Saturday Daily Thread: Resource Request and Sharing! Daily Thread

4 Upvotes

Weekly Thread: Resource Request and Sharing šŸ“š

Stumbled upon a useful Python resource? Or are you looking for a guide on a specific topic? Welcome to the Resource Request and Sharing thread!

How it Works:

  1. Request: Can't find a resource on a particular topic? Ask here!
  2. Share: Found something useful? Share it with the community.
  3. Review: Give or get opinions on Python resources you've used.

Guidelines:

  • Please include the type of resource (e.g., book, video, article) and the topic.
  • Always be respectful when reviewing someone else's shared resource.

Example Shares:

  1. Book: "Fluent Python" - Great for understanding Pythonic idioms.
  2. Video: Python Data Structures - Excellent overview of Python's built-in data structures.
  3. Article: Understanding Python Decorators - A deep dive into decorators.

Example Requests:

  1. Looking for: Video tutorials on web scraping with Python.
  2. Need: Book recommendations for Python machine learning.

Share the knowledge, enrich the community. Happy learning! šŸŒŸ


r/Python 3d ago

Showcase A new take on dependency injection in Python

13 Upvotes

In case anyone's interested, I've put together a DI framework "pylayer" in python that's fairly different from the alternatives I'm aware of (there aren't many). It includes a simple example at the bottom.
https://gist.github.com/johnhungerford/ccb398b666fd72e69f6798921383cb3f

What my project does

It allows you automatically construct dependencies based on their constructors.

The way it works is you define your dependencies as dataclasses inheriting from anĀ InjectableĀ class, where upstream dependencies are declared as dataclass attributes with type hints. Then you can just pass the classes to anĀ EnvĀ object, which you can query for any provided type that you want to use. The Env object will construct a value of that type based on theĀ InjectableĀ classes you have provided. If any dependency needed to construct the queried type, it will generate an error message explaining what was missing and why it was needed.

Target audience

This is a POC that might be of interest to anyone who is uses or has wanted to use dependency injection in a Python project.

Comparison

https://python-dependency-injector.ets-labs.org/ is but complicated and unintuitive. pylayer is more automated and less verbose.

https://github.com/google/pinject is not maintained and seems similarly complicated.

https://itnext.io/dependency-injection-in-python-a1e56ab8bdd0 provides an approach similar to the first, but uses annotations to simplify some aspects of it. It's still more verbose and less intuitive, in my opinion, than pylayer.

Unlike all the above, pylayer has a relatively simple, functional mechanism for wiring dependencies. It is able to automate more by using the type introspection and the automated __init__ provided by dataclasses.

For anyone interested, my approach is based on Scala'sĀ ZIO library. Like ZIO's ZLayer type, pylayer takes a functional approach that uses memoization to prevent reconstruction of the same values. The main difference between pylayer and ZIO is that wiring and therefore validation is done at runtime. (Obviously compile-time validation isn't possible in Python...)


r/Python 3d ago

Discussion Automatic Flowcharts

13 Upvotes

Are there any tools or libraries that make automatic flowcharts or something similar? Like the call stack when debugging but more like a diagram of all the calls that are made since an if name == '__main__' is executed. It would be useful to see more or less what a program does even if it is not completely accurate.


r/Python 3d ago

Showcase Random context generator - RaCoGen (provisional name)

3 Upvotes

What my project does:

RaCoGen is a simple program that generates a random context (a situation in which then two characters are put) by making use of 3 databases (nouns, adjectives and actions).

  1. First, it selects a random noun and adjective, and it generates a setting with that, like "big forest" or "sandy gym".
  2. Then, it selects and action, like "talking", "drawing"...
  3. Finally, it generates the context using the setting and action, giving a result like "In a sandy gym, where char1 and char2 are drawing."

After all of this is ready, the program prints the result like this:

Random noun selected: beach

Random adjective selected: cultural

Random setting created: cultural beach

Random action selected: sleeping

Random context created: In a cultural beach, where char1 and char2 are sleeping.

Target audience:

This project doesn't have a target audience in mind because it's an experiment. I'm just seeing what I can or can't do. You can consider it a toy, because it's more for entertainment than anything eslse.

But that's just for now. I will, probably, expand this so it gives the users more options, has more variety, etc.

For now, it's made to test while I learn, but maybe in the future it could turn to an app with a nice interface for users that want to make databases for whatever reason but don't want, or can't, spend the time writting everything themselves.

Comparision with other programs:

I don't know if there are any programs like this out there. My reasoning tells me that there must be, and that my program will be simpler and, because of that, you could say that worse for that regard.

Links:

If you want to give this program a try, check out my GitHub repository.

If you are interested in how it works internally and want to follow my journey as I figure these things out, check out my Google Document discussing all of that.


r/Python 3d ago

Showcase Tkinter based package for sending GUI alerts / notifications, named tk-alert

12 Upvotes

Hi everyone, I have been thinking to post here for some time and decided to do so. I was hesitant as this is my first time working on a python package and the project is far from being finished.

Long story short, I have been working on a personal app using Tkinter and I needed a way to send error notifications to users, could not find something really easy to install and use so I started working on creating my own self-contained package.

1. What my project does.

Sends GUI notifications for users meant for information, warnings or errors, using Tkinter.

My design philosophy was that the package should be simple and ready to use out-of-the-box, but should have more complex design time features for people that want a specific look on their app (this part is work in progress)

So far I did not have time to continue work on this due to multiple reasons, but as the cold season approaches I am looking forward to get on with some tasks from my to-do list.

2. Target audience.

Tkinter devs, not ready for production yet.

3. Comparison.

What I want this package to be set apart by is the ease of set-up and use + the fact that it is self-contained (I will keep it that way in all the iterations to come).

Please take a look if you want (or if this sounds like something you would use). Any feedback is appreciated as I don't have a lot of experience with making python packages and I am looking to improve my code / design.

Github: https://github.com/DragosPancescu/tk-alert

PyPI: https://pypi.org/project/tk-alert/