Python

7610 readers
2 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
26
27
28
 
 

I'm looking for a way to generate a single Markdown (.md) file that includes all the file names, function definitions, and docstrings from my Python files. Ideally, this should traverse a directory recursively while respecting the .gitignore rules.

Does anyone know of a package that accomplishes this?

29
30
 
 

An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:

31
32
5
Python bitwise operators (programming.dev)
submitted 1 month ago* (last edited 1 month ago) by bterwijn@programming.dev to c/python@programming.dev
 
 

Teaching and learning Python bitwise operators gets much easier after showing the binary representations of integers using memory_graph: bitwise operators in Memory Graph Web Debugger

Understanding of the inverse ~ operator is helped by showing the two’s complement representation.

33
 
 

I have a list of communities, each with total votes, upvote percentage, and the community name. I want to sort the list by 'engagement,' which would be some combination of total votes and upvote percentage. What is the best way to do this? What would be the best measure of 'engagement' with each community given this data?

34
 
 

Hi everyone,

I’m trying to write a Python script to fetch all the communities a specific Lemmy user is subscribed to, with one community per line.

I’ve seen examples using raw requests (like this post), but I’d like to do it using Pythorhead instead.

Has anyone done this before or can provide a simple example of how to list a user’s subscriptions using Pythorhead?

Similarly, I'd also like to get the list of communities that the user has blocked.

Thanks!

35
36
37
 
 

cross-posted from: https://lemmy.dbzer0.com/post/55501944

Hey, I’ve been kicking around an idea for a bot: it would look for fanfiction links shared in a server and keep track of which ones get shared the most.

The concept:

  • Track sites like AO3, FanFiction.net, ScribbleHub, etc.
  • Count how often each link gets posted
  • Commands to see the “top” links or which domains are tracked

It’s just a rough idea, I haven’t built it yet. Curious if anyone thinks this would actually be useful or has tips for implementing it without overcomplicating things.

import re
import json
import discord
from collections import Counter
from discord.ext import commands

TOKEN = "YOUR_BOT_TOKEN"
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

# Domain list you want to track (lower-case)
TRACK_DOMAINS = {
    "archiveofourown.org",
    "fanfiction.net",
    "forum.questionablequesting.com",
    "forums.spacebattles.com",
    "forums.sufficientvelocity.com",
    "webnovel.com",
    "hentai-foundry.com",
    "scribblehub.com",
}

link_pattern = re.compile(r'https?://\S+')

link_counter = Counter()

def domain_of_url(url: str) -> str | None:
    try:
        # Extract domain part
        from urllib.parse import urlparse
        parsed = urlparse(url)
        domain = parsed.netloc.lower()
        # remove leading “www.”
        if domain.startswith("www."):
            domain = domain[4:]
        return domain
    except Exception:
        return None

def save_links():
    with open("links.json", "w") as f:
        # convert counts to dict
        json.dump(dict(link_counter), f)

def load_links():
    try:
        with open("links.json") as f:
            data = json.load(f)
        for link, cnt in data.items():
            link_counter[link] = cnt
    except FileNotFoundError:
        pass

@bot.event
async def on_ready():
    load_links()
    print(f"Bot is ready. Logged in as {bot.user}")

@bot.event
async def on_message(message):
    if message.author.bot:
        return
    links = link_pattern.findall(message.content)
    for link in links:
        dom = domain_of_url(link)
        if dom in TRACK_DOMAINS:
            link_counter[link] += 1
    await bot.process_commands(message)

@bot.command(name="links")
async def links(ctx, top: int = 10):
    if not link_counter:
        await ctx.send("No links recorded.")
        return
    sorted_links = sorted(link_counter.items(), key=lambda x: x[1], reverse=True)
    display = sorted_links[:top]
    lines = [f"{link} — {count}" for link, count in display]
    await ctx.send("**Top links:**\n" + "\n".join(lines))

@bot.command(name="domains")
async def domains(ctx):
    """Show which domains are tracked."""
    await ctx.send("Tracked domains: " + ", ".join(sorted(TRACK_DOMAINS)))

@bot.command(name="dump")
async def dump(ctx):
    """For admin: dump full counts (might be large)."""
    if not link_counter:
        await ctx.send("No data.")
        return
    lines = [f"{link} — {cnt}" for link, cnt in sorted(link_counter.items(), key=lambda x: x[1], reverse=True)]
    chunk = "\n".join(lines)
    # Discord message length limit; you may need to split
    await ctx.send(f"All counts:\n{chunk}")

@bot.event
async def on_disconnect():
    save_links()

bot.run(TOKEN)
38
 
 

I've noticed that a lot of my projects follow the same basic architecture and I often like to write some simple tools for myself where it takes much longer to set up the project than it does to write the domain specific code. So I've been looking into scaffolding tools to help with this. I'm aware of Cookiecutter and Copier. Are there others? How do they compare? What are your preferences and why?

39
40
41
 
 

An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:

42
43
44
 
 

I'm working on a Python script to find a snappy Lemmy instance, as the one I was using (not dbzer0) has recently slowed down to about 5 seconds per page load. I have a rough version of the script, but I need to fetch a list of available Lemmy instances through their API.

Could anyone guide me on how to access the Lemmy API to retrieve a list of instances?

45
 
 

Some struggle with recursion, but as package invocation_tree visualizes the Python call tree in real time, it gets easy to understand what is going on and to debug any remaining issues.

See this one-click Quick Sort demo in the Invocation Tree Web Debugger.

46
47
 
 

Better understand the Python Data Model or Data Structures by memory_graph visualization with just one click:

48
49
 
 

cross post from: https://programming.dev/post/37369902

Hi everyone,

we, the iceoryx community, just released iceoryx2 v0.7, an ultra-low latency inter-process communication framework for Rust, C, C++ and with this release, Python.

If you are into robotics, embedded real-time systems (especially safety-critical), autonomous vehicles or just want to hack around, iceoryx2 is built with you in mind.

Check out our release announcement for more details: https://ekxide.io/blog/iceoryx2-0-7-release

And the link to the project: https://github.com/eclipse-iceoryx/iceoryx2

50
view more: ‹ prev next ›