Python
- Welcome to c/Python!
Welcome to c/Python, the go to place to discuss Python tools, techniques, and news.
We're just getting started, so please use this thread to suggest what this community should look like, what it should cover, and how it should operate.
- Python Big O: the time complexities of different data structures in Pythonwww.pythonmorsels.com Python Big O: the time complexities of different data structures in Python
The time complexity of common operations on Python's many data structures.
Trey Hunner writes:
> This article is primarily meant to act as a Python time complexity cheat sheet for those who already understand what time complexity is and how the time complexity of an operation might affect your code. For a more thorough explanation of time complexity see Ned Batchelder's article/talk on this subject.
Read Python Big O: the time complexities of different data structures in Python
- [Solved] Subclassing pathlib.PosixPath broken since Python 3.12 (actually its fixed, but workaround broken)
Solved: Thanks to a user with this reply: https://programming.dev/comment/10034690
---
cross-posted from: https://beehaw.org/post/13901165
> Hi all. I have a little problem and don't know how to solve. A CLI program in Python is broken since Python 3.12. It was working in Python 3.11. The reason is, that Python 3.12 changed how subclassing of a pathlib.Path works (basically fixed an issue), which now breaks a workaround. > > #### The class in question is: > >
python > class File(PosixPath): > def __new__(cls, *args: Any, **kwargs: Any) -> Any: > return cls._from_parts(args).expanduser().resolve() # type: ignore > > def __init__(self, source: str | Path, *args: Any) -> None: > super().__init__() > self.__source = Path(source) > > @property > def source(self) -> Path: > return self.__source > > @property > def modified(self) -> Time: > return Time.fromtimestamp(os.path.getmtime(self)) > > @property > def changed(self) -> Time: > return Time.fromtimestamp(os.path.getctime(self)) > > @property > def accessed(self) -> Time: > return Time.fromtimestamp(os.path.getatime(self)) > > # Calculate sha512 hash of self file and compare result to the > # checksum found in given file. Return True if identical. > def verify_sha512(self, file: File, buffer_size: int = 4096) -> bool: > compare_hash: str = file.read_text().split(" ")[0] > self_hash: str = "" > self_checksum = hashlib.sha512() > with open(self.as_posix(), "rb") as f: > for chunk in iter(lambda: f.read(buffer_size), b""): > self_checksum.update(chunk) > self_hash = self_checksum.hexdigest() > return self_hash == compare_hash >
> > #### and I get this error when running the script: > >> Traceback (most recent call last): > File "/home/tuncay/.local/bin/geprotondl", line 1415, in > sys.exit(main()) > ^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1334, in main > arguments, status = parse_arguments(argv) > ^^^^^^^^^^^^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1131, in parse_arguments > default, status = default_install_dir() > ^^^^^^^^^^^^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1101, in default_install_dir > steam_root: File = File(path) > ^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 97, in __new__ > return cls._from_parts(args).expanduser().resolve() # type: ignore > ^^^^^^^^^^^^^^^ > AttributeError: type object 'File' has no attribute '_from_parts'. Did you mean: '_load_parts'? >
> > #### Now replacing_from_parts
with_load_parts
does not work either and I get this message in that case: > >> Traceback (most recent call last): > File "/home/tuncay/.local/bin/geprotondl", line 1415, in > sys.exit(main()) > ^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1334, in main > arguments, status = parse_arguments(argv) > ^^^^^^^^^^^^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1131, in parse_arguments > default, status = default_install_dir() > ^^^^^^^^^^^^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 1101, in default_install_dir > steam_root: File = File(path) > ^^^^^^^^^^ > File "/home/tuncay/.local/bin/geprotondl", line 97, in __new__ > return cls._load_parts(args).expanduser().resolve() # type: ignore > ^^^^^^^^^^^^^^^^^^^^^ > File "/usr/lib/python3.12/pathlib.py", line 408, in _load_parts > paths = self._raw_paths > ^^^^^^^^^^^^^^^ > AttributeError: 'tuple' object has no attribute '_raw_paths' >
> > #### I have searched the web and don't understand how to fix this. Has anyone an idea what to do? - How Python Asyncio Works: Recreating it from Scratchjacobpadilla.com How Python Asyncio Works: Recreating it from Scratch
Learn how asyncio works by recreating it from scratch with Python generators and using the __await__ under method for the async/await keywords.
- RPi 0W - How to stop long-running action
I have a Keybow MINI hooked up to a Raspberry Pi Zero W, and I'm using Python to respond to events. I have one button that kicks off playing a song on a passive buzzer, and I'm wondering if there's a way to have a button press stop the song before it completes.
- Autorun | Autostart | Run at startup
Many commertial apps have options to run apps at logins... Is there any cross-platform way to do so in python?
- A Guide to Python Lambda Functionsadamj.eu A Guide to Python Lambda Functions - Adam Johnson
In Python, Lambda functions are rare compared to โnormalโ functions, and occasionally misunderstood or overused.
- A library for creating fully typed declarative API clients quickly and easilygithub.com GitHub - martinn/quickapiclient: A library for creating fully typed declarative API clients quickly and easily.
A library for creating fully typed declarative API clients quickly and easily. - martinn/quickapiclient
Would love to hear any suggestions, feedback or comments.
- Announcing py2wasm: A Python to Wasm compilerwasmer.io Announcing py2wasm: A Python to Wasm compiler ยท Blog ยท Wasmer
py2wasm converts your Python programs to WebAssembly, running them at 3x faster speeds
- Pyright can check exhaustiveness of match statements on unions
Twitter user @DanyX23:
TIL: pyright, the python type checking engine that is used by VS Code, has support for exhaustiveness checking for match statements with union types!
If you add the following to your pyproject.toml, you'll get the attached warning
[tool.pyright] reportMatchNotExhaustive = true
- Python Tutorials by Socratica | YouTube Playlist
Not sure if this is allowed here, and it's not my playlist, but I thought I'd post these tutorials since I've found them helpful for learning the basics.
- Why won't my Python unit tests run? [SOLVED]
Hello! I'm attempting to follow some tutorials on unit testing with Python. One of them is a video tutorial Unit Tests in Python on the Socratica channel. Everyone in the comments seems to be making out just fine, and Iโm following the instructorโs directions to the letter, yet I get a different result. Itโs driving me mad lol.
In the video, the instructor creates two text files, one called
circles.py
in which she defines a functioncircle_area(r)
, and another calledtest_circles.py
in which she writes some unit tests. In my attempt to follow along, I've ended up with two files structured like so:/home/yo_scottie_oh/Projects/PythonTutorials/Socratica/Circles โโโ circles.py โโโ test_circles.py
circles.py
:``` from math import pi
def circle_area(r): return pi*(r**2)
Test function
radii = [2, 0, -3, 2 + 5j, True, "radius"] message = "Area of circles with r = {radius} is {area}."
for r in radii: A = circle_area(r) print(message.format(radius=r,area=A)) ```
test_circles.py
:``` import unittest from circles import circle_area from math import pi
class TestCircleArea(unittest.TestCase): def test_area(self): # Test areas when radius >=0 self.assertAlmostEqual(circle_area(1),pi) self.assertAlmostEqual(circle_area(0),0) self.assertAlmostEqual(circle_area(2.1),pi*2.1**2) ```
Where I'm getting tripped up is at 4:32 in the video, the instructor says to run the unit tests by opening a shell, going to the directory that contains both the circles and test_circles modules, and issuing the following command:
python -m unittest test_circles
.Instructor's result (it runs the unit test):
``` Ran 1 test in 0.000s
OK ```
My result (it seems to execute
circles.py
itself):[yo_scottie_oh@nobara Circles]$ python -m unittest test_circles Area of circles with r = 2 is 12.566370614359172. Area of circles with r = 0 is 0.0. Area of circles with r = -3 is 28.274333882308138. Area of circles with r = (2+5j) is (-65.97344572538566+62.83185307179586j). Area of circles with r = True is 3.141592653589793. Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/usr/lib64/python3.11/unittest/__main__.py", line 18, in <module> main(module=None) File "/usr/lib64/python3.11/unittest/main.py", line 101, in __init__ self.parseArgs(argv) File "/usr/lib64/python3.11/unittest/main.py", line 150, in parseArgs self.createTests() File "/usr/lib64/python3.11/unittest/main.py", line 161, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/unittest/loader.py", line 232, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/unittest/loader.py", line 232, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/unittest/loader.py", line 162, in loadTestsFromName module = __import__(module_name) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/yo_scottie_oh/Projects/PythonTutorials/Socratica/Circles/test_circles.py", line 4, in <module> from circles import circle_area File "/home/yo_scottie_oh/Projects/PythonTutorials/Socratica/Circles/circles.py", line 14, in <module> A = circle_area(r) ^^^^^^^^^^^^^^ File "/home/yo_scottie_oh/Projects/PythonTutorials/Socratica/Circles/circles.py", line 6, in circle_area return pi*(r**2) ~^^~ TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' [yo_scottie_oh@nobara Circles]$
I've been banging my head against the wall for hours now trying to figure out why when I execute the same command as the instructor, it appears to execute my Python scripts themselves instead of running the unit tests.
Other things I've tried:
I've read the Python documentation on unit testing. I tried adding this to the end of the test_circles.py document, but that did not change anything.
if __name__ == '__main__': unittest.main()
I've tried following this other written tutorial. After I create the text documents and organize them in the separate shapes and tests folders and run the command
python -m unittest discover -v
, again I get a different result from the author.Author's result:
``` test_area (test_circle.TestCircle) ... ok test_circle_instance_of_shape (test_circle.TestCircle) ... ok test_create_circle_negative_radius (test_circle.TestCircle) ... ok test_area (test_square.TestSquare) ... ok test_create_square_negative_length (test_square.TestSquare) ... ok test_square_instance_of_shape (test_square.TestSquare) ... ok
---------------------------------------------------------------------- Ran 6 tests in 0.002s
OK ```
My result:
``` [yo_scottie_oh@nobara test]$ python -m unittest discover -v test_circle (unittest.loader._FailedTest.test_circle) ... ERROR test_square (unittest.loader._FailedTest.test_square) ... ERROR
====================================================================== ERROR: test_circle (unittest.loader._FailedTest.test_circle) ---------------------------------------------------------------------- ImportError: Failed to import test module: test_circle Traceback (most recent call last): File "/usr/lib64/python3.11/unittest/loader.py", line 419, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/unittest/loader.py", line 362, in _get_module_from_name import(name) File "/home/yo_scottie_oh/Projects/PythonTutorials/PythonUnitTesting/test/test_circle.py", line 4, in <module> from shapes.circle import Circle ModuleNotFoundError: No module named 'shapes'
====================================================================== ERROR: test_square (unittest.loader._FailedTest.test_square) ---------------------------------------------------------------------- ImportError: Failed to import test module: test_square Traceback (most recent call last): File "/usr/lib64/python3.11/unittest/loader.py", line 419, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib64/python3.11/unittest/loader.py", line 362, in _get_module_from_name import(name) File "/home/yo_scottie_oh/Projects/PythonTutorials/PythonUnitTesting/test/test_square.py", line 3, in <module> from shapes.square import Square ModuleNotFoundError: No module named 'shapes'
---------------------------------------------------------------------- Ran 2 tests in 0.000s
FAILED (errors=2) ```
So yeahโฆ this brings me to my question: Whatโs the obvious thing that everybody else gets that I'm missing? Is the tutorial outdated? Is it because the instructor is on Windows and Iโm on Linux? Why wonโt my unit tests run?
- Configuring NeoVim as a Python IDE (2023) | Siddharta Govindaraj | Sun 07 May 2023www.siddharta.me Configuring NeoVim as a Python IDE (2023)
As I blogged about in the previous two articles, I recently updated my NeoVim configuration for the fourth time. Although it might sound like a...
Siddharta Govindaraj writes:
> As I blogged about in the previous two articles, I recently updated my NeoVim configuration for the fourth time. Although it might sound like a lot of config updates, keep in mind that it happened over a period of four years. > >- The first version was a port of my existing Vim configuration. Because NeoVim is backward compatible with Vim, you can just move the configuration over and it will work >- In the second version, I migrated my plugin manager to Packer. This config was a mix of old style Vim config and the newer NeoVim style with some plugins migrated to Lua equivalents >- Then I decided to go 100% Lua config and started using Kickstart.nvim and LazyVim. >- This fourth time around I used Kickstart and LazyVim as guides to write my own from scratch. > > You can find my NeoVim configuration on Github. > > In this article I am going to go through and explain my configuration step-by-step. I have a terrible memory, so this post will also serve as a guide when I inevitably need to look through this file in the future.
- zpy: Zsh helpers for Python venvs, with uv or pip-toolsgithub.com GitHub - AndydeCleyre/zpy: Zsh helpers for Python venvs, with uv or pip-tools
Zsh helpers for Python venvs, with uv or pip-tools - AndydeCleyre/zpy
cross-posted from: https://programming.dev/post/12688262
> Hello! > > This is my little Zsh frontend for Python venv and dependency management, as well as pipx-like app installation. > > It's not new, but I just made a new release that can use uv as a backend, making it much faster (and hipper, obviously). > > If you have zpy installed, you can install uv with the
pipz
command, and from then on zpy will use uv instead of Python's venv module and pip-tools: > >zsh > % pipz install uv >
> > If you have any questions, please ask! > > I personally use it in combination with mise (for Python runtime management) and flit (for package publishing), but aim to keep it rather agnostic and interoperable. - My approach to building an open-source data tool: Python vs JavaScriptdev.to My approach to building an open-source data tool: Python vs JavaScript
When we rebootedย Latitudeย I strongly pushed the team to use Python as our main language. It was an...
Hi there ๐, Iโm Gerard, founder of Latitude.
I have written an article on how I approached building an open-source data tool. I had doubts about Python vs JavaScript, but Iโm happy with the path I chose.
Would love it if you guys give me any feedback!
- tl;dr โ Apache Software Foundation, Blender Foundation, OpenSSL Software Foundation, PHP Foundation, Rust Foundation, and Eclipse Foundation have jointly announced their intention to collaborate on
tl;dr โ Apache Software Foundation, Blender Foundation, OpenSSL Software Foundation, PHP Foundation, Rust Foundation, and Eclipse Foundation have jointly announced their intention to collaborate on the establishment of common specifications for secure software development based on existing open source best practices. https://eclipse-foundation.blog/2024/04/02/open-source-community-cra-compliance/ #opensource #cra #cybersecurity @python @rust @EclipseFdn @opensslannounce @Blender
- All-In-One {G,T}UI Python IDE with Internal MP3 Player, Idle Clicker Game & REPL
YouTube Video
Click to view this content.
Using Tkinter and Some Ninja CLI Skillz
- Coverage.py with sys.monitoringnedbatchelder.com Coverage.py with sys.monitoring
Coverage.py now has experimental support for faster Python execution monitoring in Python 3.12. Please try it out!
- jendrikseipp/vulture: Find dead Python codegithub.com GitHub - jendrikseipp/vulture: Find dead Python code
Find dead Python code. Contribute to jendrikseipp/vulture development by creating an account on GitHub.
The repo also links to some similar tools, like
coveragepy
,uncalled
, anddead
. - Dice Roller with Python using either tkinter or streamlit
the code on the website is javascript here it is, make sure to create dice images for it to work (e.g dice1.png):
``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dice Roller</title> <style> body { font-family: Arial, sans-serif; } #result-frame { margin-top: 20px; } </style> </head> <body> <h2>Dice Roller</h2> <label for="num-dice">Choose Number of Dice:</label><br><br> <select id="num-dice"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> </select> <button onclick="rollDice()">Roll</button> <div id="result-frame"></div>
<script> function rollDice() { var numDice = parseInt(document.getElementById('num-dice').value); var resultFrame = document.getElementById('result-frame'); resultFrame.innerHTML = ''; // Clear previous results
var diceImages = []; for (var i = 1; i <= 6; i++) { var img = document.createElement('img'); img.src = 'https://www.slyautomation.com/wp-content/uploads/2024/03/' + 'dice' + i + '.png'; // Change the path to match your uploaded images diceImages.push(img); }
for (var j = 0; j < numDice; j++) { var result = Math.floor(Math.random() * 6); // Random result from 0 to 5 var diceImage = diceImages[result].cloneNode(); resultFrame.appendChild(diceImage); } } </script> </body> </html> ```
- how to send the icecream output to a log file? [solved]
Hi, I'm currently using this to log my python process
logging.basicConfig(filename='filename.log', level=logging.DEBUG)
logger = logging.getLogger()
sys.stderr.write = logger.error
sys.stdout.write = logger.info
And then using print(f'{datetime.now()} log message') where I want to log.
It's working OK, buy I would like to live it to ic, but can't find any info on how to send the ic output to the logger.
Thanks for any help.
- Another program for those starting out in python ๐chat-to.dev Another program for those starting out in python ๐
This program prompts the user to input a phrase, then counts the number of vowels and consonants present in that phrase, ignoring uppercase letters and considering only alphabetical characters. ```py def count_vowels_consonants(phrase): vowels = 0 consonants = 0 # Converting the phrase ...
- Python's UV tool is even bettermicro.webology.dev Python's UV tool is even better
Last month, I wrote Pythonโs UV tool is actually pretty good about Astralโs new Python package installer and resolver uv, and this is a follow-up post. Since last month, I have added uv to over a dozen projects, and I recently learned that you could skip the venv step for projects that use container...
- looking for a pastebin / git, written in Python.
Hi,
Following my previous post where quickly share code ?
I'm looking for a pastebin / git / github self-hosted software written in ๐ Python.
Here the features that I'm looking for (anyway like it's in Python I could create my self the missing one afterward :)
- self-hosted, (but may have some instance public online)
- compatible with git (and therefore history log )
- syntax highlight for a various languages (especially ๐ Python )
- Can show the difference between versions (modified, added, removed ) with color and nice interface.
- Fully LOSS (aka FOSS)
Thanks.
- The wrong way to speed up your code with Numbapythonspeed.com The wrong way to speed up your code with Numba
Numba can make your numeric code faster, but only if you use it right.
- Help with a python script to control my lights?github.com [Example request] The most basic way to turn an individual, specific light on and off ยท Issue #185 ยท mclarkk/lifxlan
I've been struggling with this for hours, i'm not a python dev, i'm just trying to control my lights with my linux pc #!/usr/bin/env python import sys from lifxlan import LifxLAN def main (): lan =...
cross-posted from: https://lemmy.ml/post/13397153
> I'm just trying to control my smartlights with a script, it seems to be having a lot of problems, I really don't know what I'm doing, i'd appreciate any help I can get > > Once I have a script that can individually turn lights on/off i can edit the rest myself, I just can't get the base functionality working.
- Parsing a CSV file really really fast in Pythondatapythonista.me How fast can we process a CSV file
Introduction Comma-separated values (CSV) are an extremely popular format to store tabular data because of their simplicity and how easy...
If you care about performance, you may want to avoid CSV files. But since our data sources are often like our family, we can't make a choice, we'll see in this blog post how to process a CSV file as fast as possible.
- Combining Rust and Python
YouTube Video
Click to view this content.
In this video, I'll show you how to seamlessly integrate Rust with Python using Pyo3. This library allows you to write Python modules with Rust. This means that we get the speed and safety of Rust along with Python's easy-to-use features!
- Python deque tutorialmathspp.com Python deque tutorial
This tutorial teaches how to work with the Python data structure collections.deque and provides 7 example use cases.
- Write Shell Out Comes Pythongithub.com GitHub - dislux-hapfyl/pynksh: ksh python "transpiler" - write shell > python
ksh python "transpiler" - write shell > python. Contribute to dislux-hapfyl/pynksh development by creating an account on GitHub.
korn shell wrapper that outputs python code: you write shell > out comes the snake
- CPython PR merged yesterday: Allow disabling the GIL with `PYTHON_GIL=0` or `-X gil=0` by swtaarrs ยท Pull Request #116338 (part of PEP 703)github.com gh-116167: Allow disabling the GIL with `PYTHON_GIL=0` or `-X gil=0` by swtaarrs ยท Pull Request #116338 ยท python/cpython
In free-threaded builds, running with PYTHON_GIL=0 or -X gil=0 will now disable the GIL. #116322 and #116329 track follow-up work to re-enable the GIL when loading an incompatible extension, and to...
cross-posted from: https://lemmy.ml/post/13079957
> https://peps.python.org/pep-0703/
- Using Polars in a Pandas worldpythonspeed.com Using Polars in a Pandas world
Pandas has far more third-party integrations than Polars. Learn how to use those libraries with Polars dataframes.
- Communication between Raspberry Pis on different networks
I'm sorry if this isn't the place to ask this, I also asked over at !raspberrypi@lemmy.ml.
So what I want to do is this: Two RasPis are at different locations. They're on different networks but have internet access. Pressing a button on one of the Pis turns on an LED over at the other Pi via GPIO. How can I make the communication work? My first thought was Telegram bots as I'm familiar with those for notifications but you can't have Telegram bots communicate with each other, sadly. Is there a good (and secure) solution to this? Preferably using Python code and without continuous costs like server hosting, etc?
Thanks!
- bruin-data/ingestr: ingestr is a CLI tool to copy data between any databases with a single command seamlessly.github.com GitHub - bruin-data/ingestr: ingestr is a CLI tool to copy data between any databases with a single command seamlessly.
ingestr is a CLI tool to copy data between any databases with a single command seamlessly. - bruin-data/ingestr
Project home: https://bruin-data.github.io/ingestr/