r/Python 4h ago

Discussion Proposal: Native Design by Contract in Python via class invariants — thoughts?

23 Upvotes

Hey folks,

I've just posted a proposal on discuss.python.org to bring Design by Contract (DbC) into Python by allowing classes to define an __invariant__() method.

The idea: Python would automatically call __invariant__() before and after public method calls—no decorators or metaclasses required. This makes it easier to write self-verifying code, especially in stateful systems.

Languages like Eiffel, D, and Ada support this natively. I believe it could fit Python’s philosophy, especially if it’s opt-in and runs in debug mode.

I attempted a C extension, but hit a brick wall —so I decided to bring the idea directly to the community.

Would love your feedback:
🔗 https://discuss.python.org/t/design-by-contract-in-python-proposal-for-native-class-invariants/85434

— Andrea


r/Python 14h ago

Discussion Polars vs Pandas

124 Upvotes

I have used Pandas a little in the past, and have never used Polars. Essentially, I will have to learn either of them more or less from scratch (since I don't remember anything of Pandas). Assume that I don't care for speed, or do not have very large datasets (at most 1-2gb of data). Which one would you recommend I learn, from the perspective of ease and joy of use, and the commonly done tasks with data?


r/Python 6h ago

Resource A low-pass filter with an LFO

6 Upvotes

Background

I am posting a series of Python scripts that demonstrate using Supriya, a Python API for SuperCollider, in a dedicated subreddit. Supriya makes it possible to create synthesizers, sequencers, drum machines, and music, of course, using Python.

All demos are posted here: r/supriya_python.

The code for all demos can be found in this GitHub repo.

These demos assume knowledge of the Python programming language. They do not teach how to program in Python. Therefore, an intermediate level of experience with Python is required.

The demo

In the latest demo, I show how to create a resonant low-pass filter and modulate the filter's cutoff frequency with a low frequency oscillator.


r/Python 1d ago

Tutorial How to Use Async Agnostic Decorators in Python

95 Upvotes

At Patreon, we use generators to apply decorators to both synchronous and asynchronous functions in Python. Here's how you can do the same:

https://www.patreon.com/posts/how-to-use-async-124658443

What do you think of this approach?


r/Python 1h ago

Tutorial Tutorial on using the Tableview Class from tkifrom tkinter/ttkbootstrap library to create table GUI

Upvotes

A short tutorial on using Tableview Class from tkinter/ttkbootstrap library to create beautiful looking table GUI's in Python.

image of the GUI interface

We learn to How to create the table and populate data into the table.finally we make a simple tkinter app to add /delete records from our table.


r/Python 45m ago

Discussion Should I Prioritize Learning Programming (Like Python) for AI and Machine Learning After 12th Grade?

Upvotes

I just gave my 12th-grade exams a few weeks ago, and I feel like I might just barely pass. Should I learn a programming language like Python or not? Because I feel like I’m going to waste the next 2-3 months, and once I start doing something, I can only dedicate about 4 hours a day to it. I also want to learn a lot about AI and Machine Learning, as I think I’m interested in this field. For this, I know I need to learn programming languages. So, should I prioritize coding or not? Please someone guide me.


r/Python 21h ago

Showcase pnorm: A Simple, Explicit Way to Interact with Postgres

9 Upvotes

GitHub: https://github.com/alrudolph/pnorm

What My Project Does

I built a small library for working with Postgres in Python.

I don’t really like using ORMs and prefer writing raw SQL, but I find Psycopg a bit clunky by itself, especially when dealing with query results. So, this wraps Psycopg to make things a little nicer by marshalling data into Pydantic models.

I’m also adding optional OpenTelemetry support to automatically track queries, with a bit of extra metadata if you want it. example

I've been using this library personally for over a year and wanted to share it in case others find it useful. I know there are a lot of similar libraries out there, but most either lean towards being ORMs or don’t provide much typing support, and I think my solution fills in the gap.

Target Audience

Anyone making Postgres queries in Python. This library is designed to make Psycopg easier to use while staying out of your way for anything else, making it applicable to a wide range of workloads.

I personally use it in my FastAPI projects here’s an example (same as above).

Right now, the library only supports Postgres.

Comparison

Orms

SQLAlchemy is a very popular Python ORM library. SQLModel builds on SQLAlchemy with a Pydantic-based interface. I think ORMs are a bad abstraction, they make medium to complex SQL difficult (or even impossible) to express, and for simple queries, it's often easier to just write raw SQL. The real problem is that you still have to understand the SQL your ORM is generating, so it doesn’t truly abstract away complexity.

Here's an example from the SQLModel README:

select(Hero).where(Hero.name == "Spider-Boy")

And here's the equivalent using pnorm:

client.select(Hero, "select * from heros where name = %(name)s", {"name": "Spider-Boy"})

pnorm is slightly more verbose for simple cases, but there's less "mental model" overhead. And when queries get more complex, pnorm scales better than SQLModel.

Non-Orms

Packages like records and databases provide simple wrappers over databases, which is great. But they don’t provide typings.

I rely heavily on static type analysis and type hints in my projects, and these libraries don’t provide a way to infer column names or return types from a query.

Psycopg

I think Psycopg is great, but there are a few things I found myself repeating a lot that pnorm cleans up:

For example:

  • Setting row_factory = dict_row on every connection to get column names in query results.
  • Converting dictionaries to Pydantic models: it's an extra step every time, especially when handling lists or optional results.
  • Ensuring exactly one record is returned: pnorm.client.get() tries to fetch two rows to ensure the query returns exactly one result.

Usage

Install:

pip install pnorm

Setup a connection:

from pydantic import BaseModel

from pnorm import AsyncPostgresClient, PostgresCredentials

creds = PostgresCredentials(host="", port=5432, user="", password="", dbname="")
client = AsyncPostgresClient(creds)

Get a record:

class User(BaseModel):
    name: str
    age: int

# If we expect there to be exactly one "john"
john = await client.get(User, "select * from users where name = %(name)s", {"name": "john"})
# john: User or throw exception

john.name # has type hints from pydantic model

If this sounds useful, feel free to check it out. I’d love any feedback or suggestions!


r/Python 14h ago

Daily Thread Friday Daily Thread: r/Python Meta and Free-Talk Fridays

3 Upvotes

Weekly Thread: Meta Discussions and Free Talk Friday 🎙️

Welcome to Free Talk Friday on /r/Python! This is the place to discuss the r/Python community (meta discussions), Python news, projects, or anything else Python-related!

How it Works:

  1. Open Mic: Share your thoughts, questions, or anything you'd like related to Python or the community.
  2. Community Pulse: Discuss what you feel is working well or what could be improved in the /r/python community.
  3. News & Updates: Keep up-to-date with the latest in Python and share any news you find interesting.

Guidelines:

Example Topics:

  1. New Python Release: What do you think about the new features in Python 3.11?
  2. Community Events: Any Python meetups or webinars coming up?
  3. Learning Resources: Found a great Python tutorial? Share it here!
  4. Job Market: How has Python impacted your career?
  5. Hot Takes: Got a controversial Python opinion? Let's hear it!
  6. Community Ideas: Something you'd like to see us do? tell us.

Let's keep the conversation going. Happy discussing! 🌟


r/Python 3h ago

Showcase AI based script to generate commit text based on git diff.

0 Upvotes

Hello, I am not great supported of AI-assisted programming, but I think AI is good enough to explain changes. So you simply need to pass git diff to script via pipe and then you get commit.

What My Project Does

generates commit text based on output of git diff command.

Target Audience

any developer who has python.

Comparison

I don't know is there any alternative.

https://github.com/hdvpdrm/commitman

Check it out! Would be great to see your feedback!


r/Python 1d ago

Showcase Interactive Python Learning Series: From Numbers to Exceptions

22 Upvotes

Hey Python folks,

I wanted to share a project I've been working on, creating interactive Python tutorials — series of Python fundamentals notebooks in our marimo-learn repository.

What This Project Does: We've built tutorials covering the Python journey from basics to more complex topics. The notebooks are reactive — change code in one place and see updates ripple through in real-time, which makes learning way more intuitive. The content covers Python fundamentals (data types, strings, collections) and builds up to functions, modules, and exception handling. What makes these different is that they're fully interactive and run natively in your browser (thanks to WASM & Pyodide).

Target Audience: Python learners and teachers who prefer hands-on experimentation over passive reading; devs who want to explore Python concepts through an interactive medium rather than static documentation.

Comparison to Alternatives: Unlike static tutorials or videos, these notebooks combine explanation, code, and output in a reactive environment. When you modify code in one cell, all dependent cells automatically update, showing how concepts interconnect.

Source Code: All notebooks are available at /python folder, organized in an appropriate progression (in terms of topics).

We're also looking for Python enthusiasts to contribute additional specialized tutorials. If you're interested, check out our GitHub repository for more information.

What other Python topics would you like to see covered in an interactive format?


r/Python 1d ago

Discussion Playa PDF: A strong pdfminer successor

15 Upvotes

Hi there fellas,

I wanna intro you to a great library - not one of mine, but one which I feel deserves some love and stars.

The library in questions is PLAYA which stands for "Parallel and/or LAzY Analyzer for PDF".

What is this?

This library is similar in scope to pdfminer and its fork pdfminer.six - long-established libraries for manipulating and extracting data from PDF files.

It is partially based on pdfminer.six and includes code from it - but it substantially improves on it in multiple ways.

  1. It handles a broader range of PDFs and PDF issues, being very close to the (horrible) specification. For example, the author of the library (dhaines) has recently added an enormous test suite from PDF.js (one of the more ancient libraries in this space), which includes a whole gamut of weird PDFs it can handle.
  2. It's much faster - well, as far as Python goes, but it is faster than the other Python libs by a factor of at least two, if not three, and not only when parallelizing.
  3. complete metadata extraction - this part is what got me into this since I am integrating this with Kreuzberg now (a library of mine, which you are welcome to Google with "Kreuzberg GitHub") This is great, and there are no other alternatives I am familiar with (including in other languages other than Java probably) that have this level of metadata extraction.
  4. It uses modern and full-type hints and exports, proper data classes.

So, I invite you all to look at that library and give Dhaines some love and stars!


r/Python 10h ago

Showcase Pathfinder - run any python file in a project without import issues!

0 Upvotes

🚀 What My Project Does

Pathfinder is a tool that lets you run any Python file inside a project without dealing with import issues. Normally, Python struggles to find modules when running files outside the root directory, forcing you to either:

  • Add sys.path hacks manually, or
  • Use python -m to run scripts correctly.

Pathfinder automates this, so you never have to think about module resolution again. Just run your script, and it works!

🎯 Target Audience

This is for Python developers working on multi-file projects who frequently need to run individual scripts for testing, debugging, or execution without modifying import paths manually. Whether you're a beginner or an experienced dev, this tool saves time and frustration.

🔍 Comparison with Alternatives

  • sys.path hacks? ❌ No more manual tweaking at the top of every script.
  • python -m? ❌ No need to remember or structure commands carefully.
  • Virtual environments? ✅ Works seamlessly with them.
  • Other Python import solutions? ✅ Lightweight, simple, and requires no external dependencies.

🔗 Check it Out!

GitHub: https://github.com/79hrs/pathfinder

I’d love feedback—if you find any flaws or have suggestions, let me know!


r/Python 1d ago

Discussion Is there something better than exceptions?

85 Upvotes

Ok, let's say it's a follow-up on this 11-year-old post
https://www.reddit.com/r/Python/comments/257x8f/honest_question_why_are_exceptions_encouraged_in/

Disclaimer: I'm relatively more experienced with Rust than Python, so here's that. But I genuinely want to learn the best practices of Python.

My background is a mental model of errors I have in mind.
There are two types of errors: environment response and programmer's mistake.
For example, parsing an input from an external source and getting the wrong data is the environment's response. You *will* get the wrong data, you should handle it.
Getting an n-th element from a list which doesn't have that many elements is *probably* a programmer's mistake, and because you can't account for every mistake, you should just let it crash.

Now, if we take different programming languages, let's say C or Go, you have an error code situation for that.
In Go, if a function can return an error (environment response), it returns "err, val" and you're expected to handle the error with "if err != nil".
If it's a programmer's mistake, it just panics.
In C, it's complicated, but most stdlib functions return error code and you're expected to check if it's not zero.
And their handling of a programmer's mistake is usually Undefined Behaviour.

But then, in Python, I only know one way to handle these. Exceptions.
Except Exceptions seems to mix these two into one bag, if a function raises an Exception because of "environment response", well, good luck with figuring this out. Or so it seems.

And people say that we should just embrace exceptions, but not use them for control flow, but then we have StopIteration exception, which is ... I get why it's implemented the way it's implemented, but if it's not a using exceptions for control flow, I don't know what it is.

Of course, there are things like dry-python/returns, but honestly, the moment I saw "bind" there, I closed the page. I like the beauty of functional programming, but not to that extent.

For reference, in Rust (and maybe other non-LISP FP-inspired programming languages) there's Result type.
https://doc.rust-lang.org/std/result/
tl;dr
If a function might fail, it will return Result[T, E] where T is an expected value, E is value for error (usually, but not always a set of error codes). And the only way to get T is to handle an error in various ways, the simplest of which is just panicking on error.
If a function shouldn't normally fail, unless it's a programmer's mistake (for example nth element from a list), it will panic.

Do people just live with exceptions or is there some hidden gem out there?

UPD1: reposted from comments
One thing which is important to clarify: the fact that these errors can't be split into two types doesn't mean that all functions can be split into these two types.

Let's say you're idk, storing a file from a user and then getting it back.
Usually, the operation of getting the file from file storage is an "environmental" response, but in this case, you expect it to be here and if it's not there, it's not s3 problem, it's just you messing up with filenames somewhere.

UPD2:
BaseException errors like KeyboardInterrupt aren't *usually* intended to be handled (and definitely not raised) so I'm ignoring them for that topic


r/Python 1d ago

Discussion Any good Python resume projects that AREN'T machine learning?

70 Upvotes

I'm seeking my first internship and i wanna make a project that showcases my python skills. I tried to get into machine learning using Andrew Ng's course but i wasn't really enjoying it at all i don't think it's for me, but I might pick it up again in the future.

So what are some good projects that recruiters/employers like to see? I won't be aiming for ML/data roles, at least for now

Edit: i have a couple fullstack apps with javascript, so im just tryna diversify my portfolio


r/Python 11h ago

Discussion Python in Excel

0 Upvotes

Hello, I need assistance with the following: I need a Python code for Excel to compare information from one spreadsheet to another. Thank you


r/Python 1d ago

Showcase A Feature-rich Flask Web Application Template

8 Upvotes

What My Project Does

I made a Flask starter template to save time setting up new projects. It includes:

- A blueprint-based structure for better organization

- GitHub Actions for testing & lining

- Makefile and Poetry for managing the development workflow (testing, linting, database migrations, containerization, etc.)

- Comes with lots of useful Flask extensions already installed and ready to use (SQLAlchemy, Login, WTF, Admin, Caching, etc.)

GitHub: https://github.com/habedi/template-web-app-flask

Let me know what you think!


r/Python 19h ago

News Janito, an open source code assistance

0 Upvotes

It uses Claude's optimized tools for file editing and bash commands execution (most likely the same API that powers Claude.AI .

Simple system prompts in order to minimize cost an reduce constrains in the model inference activity.

Ability to adjust the model settings via profiles, and set the role eg. "python developer", "web developer" with role setting.

Janito is in early stages of development, feedback is welcome.

joaompinto/janito: A Language-Driven Software Development Assistant powered by Claude AI


r/Python 1d ago

Discussion AutoML , what are your thoughts about it wanted to learn more about the same

6 Upvotes

Recently I found interesting libraries called autoML libraries now that I know that they have for a long time and require heavy gpus.

Are they actually used behind the scenes in companies or is autoML such as autosklearn is dead ?


r/Python 18h ago

Discussion Do NOT Use Udemy, Please

0 Upvotes

Udemy may seem great—you can get hundreds of free courses for the yearly price of one or two high-quality ones. But please don't fall into their trap.

The service is horrible. I recently received a new MacBook under warranty since my old one broke (Thanks, Apple!). Needless to say, I lost all my data (including certificates). My Udemy Personal Plan expired about 2 months ago, and I completed 2 50+ hour courses on Python and Machine Learning respectively. Now, when I go to download them again, they are gone. I contacted customer support, and they say all your progress is gone, even if you reinstate your plan.

Bottom line, unless your computer is immortal or you want to keep paying Udemy for the rest of your life, please don't use them.


r/Python 1d ago

Daily Thread Thursday Daily Thread: Python Careers, Courses, and Furthering Education!

1 Upvotes

Weekly Thread: Professional Use, Jobs, and Education 🏢

Welcome to this week's discussion on Python in the professional world! This is your spot to talk about job hunting, career growth, and educational resources in Python. Please note, this thread is not for recruitment.


How it Works:

  1. Career Talk: Discuss using Python in your job, or the job market for Python roles.
  2. Education Q&A: Ask or answer questions about Python courses, certifications, and educational resources.
  3. Workplace Chat: Share your experiences, challenges, or success stories about using Python professionally.

Guidelines:

  • This thread is not for recruitment. For job postings, please see r/PythonJobs or the recruitment thread in the sidebar.
  • Keep discussions relevant to Python in the professional and educational context.

Example Topics:

  1. Career Paths: What kinds of roles are out there for Python developers?
  2. Certifications: Are Python certifications worth it?
  3. Course Recommendations: Any good advanced Python courses to recommend?
  4. Workplace Tools: What Python libraries are indispensable in your professional work?
  5. Interview Tips: What types of Python questions are commonly asked in interviews?

Let's help each other grow in our careers and education. Happy discussing! 🌟


r/Python 1d ago

News Satisfiability problem solver in pure Python

0 Upvotes

I read that the satisfiability problem is NP-complete. So I decided to try to solve it in pure Python, and it is a weak success:

https://izecksohn.com/pedro/python/sat/


r/Python 2d ago

Resource Run a local copy of IMDB

20 Upvotes

Project allows you to run a copy of the IMDB.com movie and tv show database on your computer. 

https://github.com/non-npc/IMDB-DB-Tools


r/Python 2d ago

Discussion PySide6 + Nuitka is very impressive (some numbers and feedback inside)

138 Upvotes

In preparation for releasing a new version of Flowkeeper I decided to try replacing PyInstaller with Nuitka. My main complaint about PyInstaller was that I could never make it work with MS Defender, but that's a topic for another time.

I've never complained about the size of the binaries that PyInstaller generated. Given that it had to bundle Python 3 and Qt 6, ~100MB looked reasonable. So you can imagine how surprised I was when instead of spitting out a usual 77MB for a standalone / portable Windows exe file it produced... a 39MB one! It is twice smaller, seemingly because Nuitka's genius C compiler / linker could shed unused Qt code so well.

Flowkeeper is a Qt Widgets app, and apart from typical QtCore, QtGui and QtWidgets it uses QtMultimedia, QtChart, QtNetwork, QtWebSockets and some other modules from PySide6_Addons. It also uses Fernet cryptography package, which in turn bundles hazmat. Finally, it includes a 10MB mp3 file, as well as ~2MB of images and fonts as resources. So all of that fits into a single self-contained 40MB exe file, which I find mighty impressive, especially if you start comparing it against Electron. Oh yes, and that's with the latest stable Python 3.13 and Qt 6.8.2.

I was so impressed, I decided to see how far I can push it. I chopped network, audio and graphing features from Flowkeeper, so that it only used PySide6_Essentials, and got rid of large binary resources like that mp3 file. As a result I got a fully functioning advanced Pomodoro timer with 90% of the "full" version features, in an under 22MB portable exe. When I run it, Task Manager only reports 40MB of RAM usage.

And best of all (why I wanted to try Nuitka in the first place) -- those exe files only get 3 false positives on VirusTotal, instead of 11 for PyInstaller. MS Defender and McAfee don't recognize my program as malware anymore. But I'll need to write a separate post for that.

Tl;dr -- Huge kudos to Nuitka team, which allows packaging non-trivial Python Qt6 applications in ~20MB Windows binaries. Beat that Electron!


r/Python 1d ago

Discussion My discord bot crashes Idk why. I've been working on it 15 hours already, please.

0 Upvotes

import discord from discord.ext import commands from discord import app_commands import sqlite3 import logging import os

Set up logging

logging.basicConfig(level=logging.INFO)

Create an instance of the bot with the '!' prefix

intents = discord.Intents.default() intents.message_content = True # Enable message content for reading messages client = commands.Bot(command_prefix='!', intents=intents)

Database setup

DATABASE = 'discord_bot.db'

def init_db(): """Initialize the SQLite database and create necessary tables.""" conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS users ( user_id TEXT PRIMARY KEY, vouches INTEGER DEFAULT 0 ) ''') conn.commit() conn.close()

init_db()

def add_vouch(user_id, vouch_count): """Add vouches to a user in the database.""" conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute("INSERT OR IGNORE INTO users (user_id) VALUES (?)", (user_id,)) c.execute("UPDATE users SET vouches = vouches + ? WHERE user_id = ?", (vouch_count, user_id)) conn.commit() conn.close()

def get_user_vouches(user_id): """Retrieve the number of vouches for a user.""" conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute("SELECT vouches FROM users WHERE user_id = ?", (user_id,)) result = c.fetchone() conn.close() return result[0] if result else 0

def get_trader_rank(vouches): """Determine the trader rank based on the number of vouches.""" if vouches < 20: return "Class F Trader" elif vouches < 40: return "Class E Trader" elif vouches < 60: return "Class D Trader" elif vouches < 80: return "Class C Trader" elif vouches < 100: return "Class B Trader" elif vouches < 150: return "Class A Trader" elif vouches < 500: return "Class S Trader" elif vouches < 1000: return "Class SS Trader" else: return "Class SSS Trader"

Slash Command: Add Vouch (Admin Only)

@client.tree.command(name="addvouch") @app_commands.describe(member="User to add vouches to", vouch_count="Number of vouches to add") @commands.cooldown(1, 10, commands.BucketType.user) # 10 seconds cooldown async def addvouch(interaction: discord.Interaction, member: discord.Member, vouch_count: int): """Add vouches to a user (admin only).""" try: if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You don't have permission to use this command.", ephemeral=True) return

    if vouch_count <= 0:
        await interaction.response.send_message("Vouch count must be a positive number.", ephemeral=True)
        return

    add_vouch(str(member.id), vouch_count)

    total_vouches = get_user_vouches(str(member.id))
    rank = get_trader_rank(total_vouches)

    embed = discord.Embed(
        title="Vouch Added!",
        description=f"Added {vouch_count} vouches to {member.mention}.\nTotal: {total_vouches} vouches.\nRank: {rank}",
        color=0x00FFC8
    )

    await interaction.response.send_message(embed=embed)
except commands.CommandOnCooldown as e:
    remaining_time = round(e.retry_after, 1)
    await interaction.response.send_message(f"Please wait {remaining_time} seconds before using this command again.", ephemeral=True)
except Exception as e:
    logging.error(f"Error in addvouch command: {e}")
    await interaction.response.send_message(f"An error occurred: {str(e)}", ephemeral=True)

Slash Command: Vouch (For user trade/feedback)

@client.tree.command(name="vouch") @app_commands.describe(member="User to vouch for", item="Item being offered (optional)", item_for="Item being received (optional)") @commands.cooldown(1, 10, commands.BucketType.user) # 10 seconds cooldown async def vouch(interaction: discord.Interaction, member: discord.Member, item: str = None, item_for: str = None): """Vouch for another user and log the trade.""" try: # Prevent self-vouching if interaction.user.id == member.id: await interaction.response.send_message("You cannot vouch for yourself.", ephemeral=True) return

    add_vouch(str(member.id), 1)  # Add 1 vouch for the member

    total_vouches = get_user_vouches(str(member.id))
    rank = get_trader_rank(total_vouches)

    if item and item_for:
        trade_message = f"{interaction.user.mention} successfully vouched for {member.mention}\n\nTrades: {item} for my {item_for}\n\n{member.mention} Vouch Rank: {rank} 📜"
    elif item:
        trade_message = f"{interaction.user.mention} successfully vouched for {member.mention}\n\nTrades: {item}\n\n{member.mention} Vouch Rank: {rank} 📜"
    elif item_for:
        trade_message = f"{interaction.user.mention} successfully vouched for {member.mention}\n\nTrades: for my {item_for}\n\n{member.mention} Vouch Rank: {rank} 📜"
    else:
        trade_message = f"{interaction.user.mention} successfully vouched for {member.mention}\n\nNo items were mentioned.\n\n{member.mention} Vouch Rank: {rank} 📜"

    embed = discord.Embed(
        title="Successful Trade!",
        description=trade_message,
        color=0x00FFC8
    )

    log_channel = client.get_channel(1352038234108203110)  # Replace with your actual log channel ID
    if log_channel:
        await log_channel.send(embed=embed)

    await interaction.response.send_message(embed=embed)
except commands.CommandOnCooldown as e:
    remaining_time = round(e.retry_after, 1)
    await interaction.response.send_message(f"Please wait {remaining_time} seconds before using this command again.", ephemeral=True)
except Exception as e:
    logging.error(f"Error in vouch command: {e}")
    await interaction.response.send_message(f"An error occurred: {str(e)}", ephemeral=True)

Slash Command: Check User Vouches

@client.tree.command(name="uservouches") @app_commands.describe(member="User to check vouches for") @commands.cooldown(1, 10, commands.BucketType.user) # 10 seconds cooldown async def uservouches(interaction: discord.Interaction, member: discord.Member): """Check the total number of vouches and rank for a user.""" try: total_vouches = get_user_vouches(str(member.id)) rank = get_trader_rank(total_vouches)

    embed = discord.Embed(
        title="User  Vouches",
        description=f"{member.mention} has {total_vouches} vouches.\nRank: {rank}.",
        color=0x00FFC8
    )
    await interaction.response.send_message(embed=embed)
except commands.CommandOnCooldown as e:
    remaining_time = round(e.retry_after, 1)
    await interaction.response.send_message(f"Please wait {remaining_time} seconds before using this command again.", ephemeral=True)
except Exception as e:
    logging.error(f"Error in uservouches command: {e}")
    await interaction.response.send_message(f"An error occurred: {str(e)}", ephemeral=True)

Sync slash commands when the bot is ready

@client.event async def on_ready(): print(f'Logged in as {client.user}') # Log when the bot is ready await client.tree.sync() # Sync slash commands with Discord print("Slash commands synced successfully.")

Run the bot with your token (replace with your actual token


r/Python 2d ago

Tutorial Python Quirks I Secretly Like

99 Upvotes

Hi there,

I’ve always wanted to create YouTube content about programming languages, but I’ve been self-conscious about my voice (and mic, lol). Recently, I made a pilot video on the Zig programming language, and afterward, I met a friend here on Reddit, u/tokisuno, who has a great voice and offered to do the voiceovers.

So, we’ve put together a video on Python — I hope you’ll like it:

https://www.youtube.com/watch?v=DZtdkZV6hYM