r/pythoncoding • • Dec 07 '22

How to write tests in Python using doctest

Thumbnail
snyk.io
13 Upvotes

r/pythoncoding • • Nov 10 '22

benchmark-imports: CLI tool to record how much time it takes to import each dependency in a Python project

Thumbnail
github.com
13 Upvotes

r/pythoncoding • • Jul 12 '21

PEP 664 -- Python 3.11 Release Schedule

Thumbnail
python.org
13 Upvotes

r/pythoncoding • • Feb 16 '25

Been working on tiny AI models in Python, curious what y’all think

12 Upvotes

AI feels way bigger than it needs to be these days. Giant LLMs, expensive fine-tuning, cloud APIs that lock you in. But for a lot of tasks, you don’t need all that, you just need a small model that works.

Been building SmolModels, an open-source Python repo that helps you build AI models from scratch. No fine-tuning, no massive datasets, just structured data, an easy training pipeline, and a small, efficient model at the end. Works well for things like classification, ranking, regression, and decision-making tasks.

Repo’s here: SmolModels GitHub. Would love to hear if others are building small models from scratch instead of defaulting to LLMs or AutoML. What’s been working for you?


r/pythoncoding • • May 15 '23

Taipy: an Open-Source Python Library to create Web Apps with Python Only

Thumbnail
github.com
12 Upvotes

r/pythoncoding • • Sep 29 '22

Lazy function calls with a generator and a monad

12 Upvotes

I went down a rabbit hole at work (again) and put this together. I thought it was interesting even if I'm not sure I should use it; hopefully some of you will find it interesting, also.

Inspired by Rust (and taking many cues from Haskell), I implemented Rust's Result type as an abstract class with two implementations, Ok and Fail. Very briefly for those not familiar, the Result type is Rust's error-handling system. It provides a fluent API that allows processing data from successful operations without having to extract that data, as well as recovering from errors without interrupting the program's flow to unwind the stack and raise an exception. I personally find it very nice to work with, even if I can't quite get all the benefits in Python.

As an evolution of the idea, I wanted to be able to not only chain together function calls and their error handlers, but to do so in a lazy fashion and have the ability to retry an operation that failed before continuing down the chain. Retry, especially, cannot be done without breaking up the fluent method chaining, which sometimes defeats the purpose.

I honestly don't know if this will actually be useful, but it was definitely interesting to figure out.

Below is a minimal but working example:

import collections.abc
from abc import ABC, abstractmethod
from typing import Any

class Result(ABC):
    value: Any

    def __init__(self, value):
        self.wrap(value)

    def wrap(self, value):
        """Equivalent to `return` in Haskell."""
        self.value = value

    def unwrap(self):
        return self.value

    @abstractmethod
    def fmap(self, func, *args, **kwargs):
        """Sometimes called "flatmap" or just "map" in other languages.
        Essentially takes any function, passes in `self.value` as arg0,
        evaluates it, and returns the result wrapped in a `Result` instance.

        Rust calls this `map`.
        """
        ...

    @abstractmethod
    def fmap_err(self, func, *args, **kwargs):
        """Sometimes called "flatmap" or just "map" in other languages.
        Essentially takes any function, passes in `self.value` as arg0,
        evaluates it, and returns the result wrapped in a `Result` instance.
        """
        ...

    def join(self, other):
        """In this limited example, "joining" two Results just means returning
        the other result's value. The idea is to be able to use functions that
        return a `Result` on their own. Using the `fmap` method on such a
        function produces a `Result[Result[T]]`; `join(self.unwrap())` should
        flatten this to `Result[T]`.
        In a less trivial program, this method might demand more complicated
        logic.
        """
        if isinstance(other, Result):
            return other
        else:
            return self.wrap(other)

    @abstractmethod
    def bind(self, func, *args, **kwargs):
        """Essentially the composition of `fmap` and `join`, allowing easy
        use of functions that already return a `Result`.
        In this example it will be implemented so that it can work with the same
        functions as `fmap` in addition to `Result`-returning functions.

        Haskell denotes this with the `>>=` operator. In Rust, it is called
        `and_then`.
        """
        ...


class Ok(Result):
    def fmap(self, func, *args, **kwargs):
        try:
            res = func(self.unwrap(), *args, **kwargs)
            return Ok(res)
        except Exception as e:
            return Fail(e)

    def fmap_err(self, func, *args, **kwargs):
        return self

    def bind(self, func, *args, **kwargs):
        res = self.fmap(func, *args, **kwargs)
        if isinstance(res.unwrap(), Result):
            return self.join(res.unwrap())
        else:
            return res


class Fail(Result):
    def fmap(self, func, *args, **kwargs):
        return self

    def fmap_err(self, func, *args, **kwargs):
        try:
            res = func(self.unwrap(), *args, **kwargs)
            return Fail(res)
        except Exception as e:
            return Fail(e)

    def bind(self, func, *args, **kwargs):
        return self


class LazyResult(collections.abc.Generator):
    def __init__(self, queue=None):
        self.results = []
        self.queue = [] if not queue else queue
        self.current_index = 0

    def enqueue(self, func, *args, **kwargs):
        self.queue.append((func, args, kwargs))

    def dequeue(self, index):
        if index is None:
            return self.queue.pop()
        else:
            return self.queue.pop(index)

    def throw(self, exc, val=None, tb=None):
        super().throw(exc, val, tb)

    def send(self, func, *args, **kwargs):
        """May take a function and its args and will run that in this
        iteration, deferring whatever was next in the queue to the next
        iteration.

        If `func` is an `int`, instead, the generator will "skip" to that
        point in the queue. Optionally, the arguments for the function at
        the new queue point may be overwritten.
        """
        if callable(func):
            self.queue.insert(
                self.current_index, (func, args, kwargs),
            )
        elif isinstance(func, int):
            self.current_index = func
            if args or kwargs:
                f, _, _ = self.queue[self.current_index]
                self.queue[self.current_index] = f, args, kwargs
        try:
            idx = self.current_index
            f, a, kw = self.queue[idx]
            if idx == 0:
                res = Ok(None).bind(lambda _: f(*a, **kw))
                self.results.append(res)
            else:
                res = self.results[idx - 1].bind(f, *a, **kw)
                if idx + 1 > len(self.results):
                    self.results.append(res)
                else:
                    self.results[idx] = res
        except IndexError:
            raise StopIteration from None
            # N.B. this doesn't actually close the generator.
            # If you do `send(0)`, it will restart from the beginning.
        else:
            self.current_index += 1
            return res

# Now for some trivial functions to demonstrate with
def first():
    return Ok(1)

def second(i):
    return i + 3

def third(m, i):
    return m / i

lr = LazyResult([(first, (), {})])
lr.enqueue(second)
lr.enqueue(third, 0)
lr.enqueue(third, 2)

# and a trivial for-loop
for r in lr:
    try:
        print('Index:', lr.current_index - 1, 'result:', r.unwrap())
        # - 1 because the index has advanced when the result is available
        if isinstance(r.unwrap(), Exception):
            raise r.unwrap()
    except Exception:
        print('Retry:', lr.current_index - 1, 'result:',
              lr.send(lr.current_index - 1, 2).unwrap())
        continue

# Index: 0 result: 1
# Index: 1 result: 4
# Index: 2 result: division by zero
# Retry: 2 result: 2.0
# Index: 3 result: 1.0

r/pythoncoding • • May 04 '22

You Should Compile Your Python And Here's Why

Thumbnail glyph.twistedmatrix.com
12 Upvotes

r/pythoncoding • • Feb 24 '22

5 Lark features you probably didn't know about

Thumbnail
blog.erezsh.com
12 Upvotes

r/pythoncoding • • Dec 23 '21

PEP 678 -- Enriching Exceptions with Notes

Thumbnail
python.org
12 Upvotes

r/pythoncoding • • Nov 02 '21

PEP 672 -- Unicode-related Security Considerations for Python

Thumbnail
python.org
12 Upvotes

r/pythoncoding • • Oct 26 '21

I have a small project rebuilding a web scraper that stopped working, it collects data telling if users have been using their wearable device for a study - no HIPAA issues. It’s about 1 or 2 weeks maximum and pays $50/hr or flat $4k. Referral fee and more info inside...

12 Upvotes

The only programmer I have available is truly over taxed with limited python experience and I don’t want him stressing about this. I need to find someone experienced who does good work and works well with a team. Must be able to get started by end of this week and completed by mid November - it was originally built in a week. Please DM me a link to your GitHub to be considered. Will pay $200 referral fee to help me find someone good - they must have seen the post, be experienced in Python, finish the project and give me your username so I know who to contact for payment. It can also be a signing bonus if you do the gig yourself.

We are a real company in Santa Barbara, CA - Opuslogica.com

Thank you to the sub and moderators for allowing me to post this.


r/pythoncoding • • Aug 23 '21

/r/PythonCoding bi-weekly "What are you working on?" thread

12 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Jun 28 '21

Making an Instagram Post Bot using Python & Instagram Graph API

Thumbnail
youtu.be
12 Upvotes

r/pythoncoding • • Jun 10 '21

Python sentinel objects, type hints, and PEP 661

12 Upvotes

Hi there!

I posted a link to PEP 661 to r/python a few days ago, and somehow it got over 100 comments.

Because I wrote some ELI5-style comments in that thread, I gathered them into an article. After a brief explanation of what sentinel objects are, I discuss how to use them with type hints, give a PEP 661 TL;DR, and then ramble a bit about PEPs in general.

If you're interested, give it a read, I'll be around to answer any question :)


r/pythoncoding • • May 03 '21

/r/PythonCoding bi-weekly "What are you working on?" thread

12 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • Apr 19 '21

Update on my project to debug and visualize Python code by using a combination of conventional static analysis tools and the attention based AI model. - Please ask me any questions!

12 Upvotes

Here is an update on my Python Project, last time I posted here there were a couple bugs and it was not functioning correctly. As of now everything should be up and running and I was hoping to get some constructive criticism on how the tool works. I thought people in this subreddit would be interested

A few repositories I visualized as an example are:

https://metabob.com/gh/galt2x/sherlock

https://metabob.com/gh/galt2x/fastapi

The program works best on Google Chrome, If you would like to check out the website, it is metabob.com


r/pythoncoding • • Jan 10 '21

Discussion of PEP 647 -- User-Defined Type Guards

12 Upvotes

Greetings everyone,

Recently PEP 647 -- User-Defined Type Guards was published as a proposal for Python 3.10.

The proposal moves Python one more step towards more stricter typing, a divisive topic in the Python community. The proposal suggests a new TypeGuard type as an alias of the bool.

Although I'm personally a big fan of type hints and the likes (from a background in TypeScript), I'm not entirely sold on this proposal yet.

I'm curious what your thoughts are on this PEP and on Python type hints in general.


r/pythoncoding • • Dec 23 '20

Beginners Guide to Tweepy

Thumbnail
loginradius.com
12 Upvotes

r/pythoncoding • • Mar 09 '25

My JARVIS Project .

11 Upvotes

Hey everyone! So I’ve been messing around with AI and ended up building Jarvis , my own personal assistant. It listens for “Hey Jarvis” , understands what I need, and does things like sending emails, making calls, checking the weather, and more. It’s all powered by Gemini AI and ollama . with some smart intent handling using LangChain.

Github

- Listens to my voice 🎙️

- Figures out if it needs AI, a function call , agentic modes , or a quick response

- Executes tasks like emailing, news updates, rag knowledge base or even making calls (adb).

- Handles errors without breaking (because trust me, it broke a lot at first)

- **Wake word chaos** – It kept activating randomly, had to fine-tune that

- **Task confusion** – Balancing AI responses with simple predefined actions , mixed approach.

- **Complex queries** – Ended up using ML to route requests properly

Review my project , I want a feedback to improve it furthure , i am open for all kind of suggestions.


r/pythoncoding • • Jul 15 '22

Making Heatmaps

Thumbnail
tech.marksblogg.com
11 Upvotes

r/pythoncoding • • Jun 13 '22

/r/PythonCoding bi-weekly "What are you working on?" thread

11 Upvotes

Share what you're working on in this thread. What's the end goal, what are design decisions you've made and how are things working out? Discussing trade-offs or other kinds of reflection are encouraged!

If you include code, we'll be more lenient with moderation in this thread: feel free to ask for help, reviews or other types of input that normally are not allowed.

This recurring thread is a new addition to the subreddit and will be evaluated after the first few editions.


r/pythoncoding • • May 22 '22

The unreasonable effectiveness of f‍-‍strings and re.VERBOSE

Thumbnail death.andgravity.com
11 Upvotes

r/pythoncoding • • Apr 22 '22

Caching techniques in asynchronous Python applications

Thumbnail
medium.com
11 Upvotes

r/pythoncoding • • Nov 17 '21

Lark 1.0 released - a parsing toolkit that is friendly, production-ready, and comprehensive.

Thumbnail self.python
11 Upvotes