r/pythoncoding • u/geraldC13 • Dec 07 '22
How to write tests in Python using doctest
r/pythoncoding • u/geraldC13 • Dec 07 '22
r/pythoncoding • u/0rsinium • Nov 10 '22
r/pythoncoding • u/audentis • Jul 12 '21
r/pythoncoding • u/Pale-Show-2469 • Feb 16 '25
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 • u/Alyx1337 • May 15 '23
r/pythoncoding • u/Delta-9- • Sep 29 '22
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.0r/pythoncoding • u/genericlemon24 • May 04 '22
r/pythoncoding • u/erez27 • Feb 24 '22
r/pythoncoding • u/genericlemon24 • Dec 23 '21
r/pythoncoding • u/genericlemon24 • Nov 02 '21
r/pythoncoding • u/forgotone • Oct 26 '21
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 • u/AutoModerator • Aug 23 '21
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 • u/[deleted] • Jun 28 '21
r/pythoncoding • u/genericlemon24 • Jun 10 '21
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 • u/AutoModerator • May 03 '21
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 • u/bobcodes247365 • Apr 19 '21
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 • u/audentis • Jan 10 '21
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 • u/pareek-narendra • Dec 23 '20
r/pythoncoding • u/cython_boy • Mar 09 '25
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.
- 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 • u/AutoModerator • Jun 13 '22
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 • u/genericlemon24 • May 22 '22
r/pythoncoding • u/ValiaHavryliuk • Apr 22 '22