Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Help Needed with fixing indentation error in Flask + Twilio Al Webhook (Python)


Hey everyone, I need some help with a Python Flask app that connects Twilio to OpenAl's GPT-4 for Al-powered phone calls
Pleaaase I feel I'm so close to figuring this out lol

The Problem-
• I keep getting IndentationError: unindent does not match any outer indentation level when running app.py • I suspect there's a mix of tabs and spaces in my file, but I can't figure out where • I tried manually fixing the indentation and even used sed to replace tabs with spaces, but the error is still there

What I Have-
• A Linux system with a Python virtual environment (venv) • A working Twilio account and OpenAl API key • The app.py script (I can share the full code if needed)

What I Need-
Someone to review my script, fix the indentation issue, and ensure it runs correctly. • If needed, help me set up a proper environment (Flask, Twilio API, OpenAl API). • Guide me on best practices for avoiding indentation errors in the future

Would really appreciate anyone willing to help either through text guidance or screen share! Any type of tip helps

/r/flask
https://redd.it/1j03e39
snakeHDL: A simple tool for creating digital logic circuits in Python

# What My Project Does

snakeHDL is a new library for creating digital logic circuits in Python with a focus on simplicity and accessibility.

There are two main components to snakeHDL. It's an API for expressing abstract trees of boolean logic, and it's also an optimizing compiler for converting these logic trees into hardware. So far the compiler can output Verilog, VHDL, and dill-pickled Python functions (for unit testing purposes).

You can find the project on GitHub, along with documentation and examples to help you learn how to use it. You can also `$ pip install snakehdl` if you don't want to clone the repo.

I uploaded a demo video to YouTube: https://www.youtube.com/watch?v=SjTPqguMc84

We are going to use snakeHDL to build parts of the Snake Processing Unit, an idea for a Python bytecode interpreter implemented in hardware to serve as a mega-fast Python coprocessor chip.

# Target Audience

I don't think snakeHDL is likely to displace the industry heavyweights for professional circuit design, but if you're a real hardware engineer I'd be interested to hear what you think. Other than that, the project is mainly intended for hackers, makers, and educators to have a quick, simple, and fun way to prototype logic circuits in Python.

# Comparison

There are

/r/Python
https://redd.it/1j0geal
D How do you write math heavy ML papers?

People who published theory ML papers or math heavy papers at ICLR/NeurIPS/ICML, how do you write math heavy papers? What is the strategy to write the method section?

/r/MachineLearning
https://redd.it/1j0efdm
Saturday Daily Thread: Resource Request and Sharing! Daily Thread

# 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
https://redd.it/1j0m7aq
Python for JS Developer: Recommendations for Learning Path or Resources?

Hello fellow Redditors!

I'm primarily a JavaScript developer with some practical Python experience.

I'd like to refresh my skills, or 'reacquaint' myself, if you will. In short, what project-based learning resources or books would you recommend to get back into Python development?

Thank you very much in advance!

/r/Python
https://redd.it/1j0b0tl
D Visual explanation of "Backpropagation: Differentiation Rules Part 3

Hi,

I previously shared part 1 and part 2 of the post here:

1. Part 1: https://www.reddit.com/r/MachineLearning/comments/1irs3gn/d\_visual\_explanation\_of\_backpropagation/
2. Part 2: https://www.reddit.com/r/MachineLearning/comments/1iy0d47/d\_visual\_explanation\_of\_backpropagation\_forward/

Here is the part 3 where I share how to derive the differentiation rules from scratch using the computation graph.

While learning the backpropagation, I realized that x\^n can be derived from the product rule x1*x2*..*xn where xi(x)=x. I found it quite interesting, hence sharing.

Thanks,

/r/MachineLearning
https://redd.it/1j0ez5y
FanBase-apui released

Just released fanbase-api — an unofficial FanBase API wrapper.

It supports:

Login & token authentication

Fetching user data

Sending private messages

Liking & commenting


The library will keep getting better with more features until it covers everything users need.

GitHub: https://github.com/nfrx1/fanbase-api
Contributions and feedback are welcome.

/r/Python
https://redd.it/1j02hnp
Text-Parable : Text-based Interactive Narrative Game

##What My Project Does
Text Parable is a text-based interactive narrative game. Inspired by The Stanley Parable, this game presents a branching story with multiple endings. Enjoy an engaging narrative experience complete with a typewriter text effect and intuitive arrow-key navigation for making choices.

If you are interested in, try it!

Github : https://github.com/tanczacy-ziemniak/Text-Parable

##Target Audience
It's just a toy project for fun.

##Comparison
It has achievement features?

/r/Python
https://redd.it/1j0uvre
[R] marsopt: Mixed Adaptive Random Search for Optimization

**marsopt** (Mixed Adaptive Random Search for Optimization) is designed to address the challenges of optimizing complex systems with multiple parameter types. The library implements an adaptive random search algorithm that dynamically balances exploration and exploitation through:

* Adaptive noise for efficient parameter space sampling
* Elite selection mechanisms to guide search toward promising regions
* Integrated support for log-scale and categorical parameters
* Flexible objective handling (minimization or maximization)

# Technical Highlights

Our benchmarking shows that marsopt achieves remarkable performance:

**Up to 150× faster** than Optuna's TPE sampler in optimization tasks with 10 floating-point parameters

[timing results](https://preview.redd.it/s4nw6eehq1me1.png?width=4395&format=png&auto=webp&s=2b51adfc1325acf7b410345ec877a18ab562d7ce)

**Consistently top ranks** across standard black-box optimization benchmarks from [SigOpt evalset](https://github.com/sigopt/evalset)

[ranks ](https://preview.redd.it/2ckzh7skq1me1.png?width=4469&format=png&auto=webp&s=a7dda9a23311fab819c672e7df78bc5eb19619b9)

# Comprehensive Variable Support

The library handles the complete spectrum of parameter types required for modern ML pipelines:

* **Continuous variables** (with optional log-scale sampling)
* **Integer variables** (with appropriate neighborhood sampling)
* **Categorical variables** (with intelligent representation)

# Practical ML Application

In our experiments with LightGBM hyperparameter tuning on the California Housing dataset, marsopt showed promising results compared to well-established optimizers like Optuna. The library efficiently handled both simple parameter spaces and more complex scenarios involving different boosting types, regularization parameters, and sampling configurations.

[california housing benchmark optuna tpe vs marsopt](https://preview.redd.it/c6nuabeqq1me1.png?width=4495&format=png&auto=webp&s=2dcdea65a86c7ef39d5b64ad5a322e8ff43011ab)

Using marsopt is straightforward:

from marsopt import Study, Trial
import numpy

/r/MachineLearning
https://redd.it/1j0vsct
How to fix Websocket handshake failed

I am working on a chat app using Django channels and the Websocket code is handled by JavaScript but no matter how I change the code I get the same handshake failed error.
On the console it says the chat is not found
I am using uvicorn instead of Daphne
Somebody help me

/r/djangolearning
https://redd.it/1j0x0et
marsopt: Mixed Adaptive Random Search for Optimization

marsopt (Mixed Adaptive Random Search for Optimization) is a flexible optimization library designed to tackle complex parameter spaces involving continuous, integer, and categorical variables. By adaptively balancing exploration and exploitation, marsopt efficiently hones in on promising regions of the search space, making it an ideal solution for hyperparameter tuning and black-box optimization tasks.

**marsopt GitHub Repository**

# What marsopt Does

Adaptive Random Search: Utilizes a mixture of random exploration and elite selection to efficiently navigate large parameter spaces.
Mixed Parameter Support: Handles floating-point (with log-scale), integer, and categorical variables in a unified framework.
Balanced Exploration & Exploitation: Dynamically adjusts sampling noise and strategy to home in on optimal regions without getting stuck in local minima.
Flexible Objective Handling: Supports both minimization and maximization objectives, adapting seamlessly to various optimization tasks.

# Key Features

1. Dynamic Noise Adaptation: Automatically scales the search around promising areas, refining parameter estimates.
2. Elite Selection: Retains top-performing trials to guide subsequent searches more effectively.
3. Log-Scale & Categorical Support: Efficiently explores a wide range of values, including complex discrete choices.
4. Performance Optimization: Demonstrates up to 150× faster performance compared to Optuna’s TPE sampler for certain continuous parameter optimizations.
5. Scalable & Versatile: Excels in both small, focused searches and extensive, high-dimensional parameter

/r/Python
https://redd.it/1j0vwru
Flask Async Mail

🚀 Introducing Flask-Async-Mail! 📧

Hey everyone! I just released Flask-Async-Mail, a lightweight and flexible asynchronous email-sending library for Flask apps using Celery. 🎉

🔹 Features:
Supports both synchronous & asynchronous email sending
Works with Celery & Redis
Supports plaintext & HTML emails
Simple setup & easy integration with Flask

👉 Try it out & contribute!
📦 PyPI: https://pypi.org/project/flask-async-mail/
💻 GitHub: https://github.com/manitreasure1/flas-async-mail.git

I’d love your feedback, contributions, and stars on GitHub! Let’s build something awesome together. 🚀🔥

\#Flask #Python #Async #Email #OpenSource

/r/flask
https://redd.it/1j10wib
Help Needed: Improving My Flask + Celery Email Library for Open Source

Hey everyone,

I'm building an **open-source Python library** that integrates **Flask and Celery** for handling asynchronous email sending. The goal is to make it simple for Flask users to:
Initialize Celery with their Flask app
Configure SMTP settings dynamically via `app.config`
Send emails asynchronously using Celery tasks

**Current Structure:**
1️⃣ **FlaskCelery** \- A wrapper to initialize Celery with Flask
2️⃣ **SendMail** \- Handles SMTP configuration and sending emails
3️⃣ **Celery Task** \- Sends emails asynchronously (without retry logic)

# What I Need Help With:

🔹 Ensuring the Celery task integrates smoothly with Flask's configuration
🔹 Best practices for handling SMTP settings securely
🔹 Optimizing the structure for maintainability and scalability

[demo.py](http://demo.py)

app.config["SMTP_HOST"]=os.environ.get('SMTP_HOST')
app.config["USE_TLS"]=os.environ.get('USE_TLS')
app.config["USE_SSL"]=os.environ.get('USE_SSL')
app.config["SENDER"]=os.environ.get('SENDER')
app.config["PASSWORD"] =os.environ.get('PASSWORD')


celery = FlaskCelery()
celery.init_app(app)
mailer = SendMail(app.config.items())


u/celery.task
def send_client_mail():
        mailer.send_email(
        subject="Hello, I'am FlaskCelery",


/r/flask
https://redd.it/1j0yrwq
PhotoFF a CUDA-accelerated image processing library

Hi everyone,

I'm a self-taught Python developer and I wanted to share a personal project I've been working on: PhotoFF, a GPU-accelerated image processing library.

## What My Project Does

PhotoFF is a high-performance image processing library that uses CUDA to achieve exceptional processing speeds. It provides a complete toolkit for image manipulation including:

- Loading and saving images in common formats
- Applying filters (blur, grayscale, corner radius, etc.)
- Resizing and transforming images
- Blending multiple images
- Filling with colors and gradients
- Advanced memory management for optimal GPU performance

The library handles all GPU memory operations behind the scenes, making it easy to create complex image processing pipelines without worrying about memory allocation and deallocation.

## Target Audience

PhotoFF is designed for:

- Python developers who need high-performance image processing
- Data scientists and researchers working with large batches of images
- Application developers building image editing or processing tools
- CUDA enthusiasts interested in efficient GPU programming techniques

While it started as a personal learning project, PhotoFF is robust enough for production use in applications that require fast image processing. It's particularly useful for scenarios where processing time is critical or where large numbers of images need to be processed.

## Comparison with Existing Alternatives

Compared to existing Python image processing libraries:

- vs. Pillow/PIL:

/r/Python
https://redd.it/1j13hm4
Sunday Daily Thread: What's everyone working on this week?

# 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
https://redd.it/1j1dkk8
Just Published Video demonstrating How To Create Weather App in Django Using OpenWeatherMap API
Let me know your thoughts on this.

Want to build a weather app using Django? In this tutorial, I’ll show you step-by-step how to create a weather application using Django and the OpenWeatherMap API. This is a beginner-friendly project that will help you understand API integration, Django views, templates, and more!

What You’ll Learn:


How to set up a Django project
How to fetch weather data using the OpenWeatherMap API
How to display real-time weather data in Django templates
How to handle user input and API requests in Django

Prerequisites: Basic knowledge of Python & Django

If you find this video helpful, please like, comment, and subscribe!

https://www.youtube.com/watch?v=FwEnjw228Ng&t=694s

/r/django
https://redd.it/1j16e72
Why am I facing this issue with CSRF ?

I do have decent experience in django but working first time on django+React, so couldn't get my head around this problem even after lot of research on internet.
I would be grateful if you guys can help me out on this one

So I have been trying to develop this Django + React app and deploy it on [repl.it](http://repl.it)

The URL for my hosted frontend is of form "SomethingFrontend.replit.app"
and for backend, it would be "SomethingBackend.replit.app"

below are the relevant settings from my settings.py:

ALLOWED_HOSTS = [".replit.dev", ".replit.app"]
CSRF_TRUSTED_ORIGINS = [
"https://SomethingFrontend.replit.app",
"https://*.replit.dev", "https://*.replit.app"
]

CORS_ALLOWED_ORIGINS = [
"https://SomethingFrontend.replit.app"
]
CORS_ALLOW_CREDENTIALS = True

SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_DOMAIN = ".replit.app"
CSRF_COOKIE_DOMAIN = ".replit.app"



I am also using django all-auth headless for social authentication via google and linkedIn
so

/r/django
https://redd.it/1j1jc4l
TIL you can use else with a while loop

Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable

This will execute when the while condition is false but not if you break out of the loop early.

For example:

Using flag

nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0

while i < len(nums):
if nums[i] == target:
found = True
print("Found:", target)
break
i += 1

if not found:
print("Not found")


Using else

nums = [1, 3, 5, 7, 9]
target = 4
i = 0

while i < len(nums):
if nums[i] == target:
print("Found:", target)
break
i += 1
else:
print("Not found")


/r/Python
https://redd.it/1j1axht
What algorithm does math.factorial use?

Does math.factorial(n) simply multiply 1x2x3x4…n ? Or is there some other super fast algorithm I am not aware of? I am trying to write my own fast factorial algorithm and what to know it’s been done

/r/Python
https://redd.it/1j1r2j7
I Built a Localization Helper Tool for Localizers/Translators

Hey everyone,

Last month, while localizing a game update, I found it frustrating to track which keys still needed translation. I tried using various AI tools and online services with massive token pools, but nothing quite fit my workflow.

So, I decided to build my own program, a Localization Helper Tool!

What My Project Does: This app detects missing translation keys after a game update and displays each missing key. I also added an auto-machine translation feature, but most won't need that, I assume (you still need a Google Cloud API key for that).

Target Audience: This tool is primarily for game developers and translators who work with localization files and need to quickly identify missing translations after updates.

Comparison: Unlike general translation services or complex localization platforms, my tool specifically focuses on detecting missing keys between versions. Most existing solutions I found were either too complex (full localization suites) or too basic (simple text comparison tools). My tool bridges this gap.

It's my first app, and I've made it with the help of GitHub Copilot, so I don't know if the file structure and code lengths for each file are good or not, but nevertheless, it works as it should.

I'd love to hear your thoughts

/r/Python
https://redd.it/1j1s5zt