Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Posts tagged python
Consider this code example: def example(param=[]): param.append('value') print(param) When example is repeatedly called with an existing list, it repeatedly appends to the list, as ...
Is there a Python serialization format that has capabilities similar to Pickle, but is text based? The problem I always have with pickle is that it's binary, so I can't manually view or edit the d...
Background Many Python programs now recommend installing with pipx, and there is a sense that you shouldn't install with pip anymore, you should use tools like pipx. Main Question However, what ...
I regularly run into the problem that I have a Python function that I want to use in both, eager and graph execution mode. I therefore have to adjust the code so that it can handle both situations....
TL;DR Is (a and b) equivalent to tf.logical_and(a, b) in terms of optimization and performance? (a and b are tensorflow tensors) Details I use Python with Tensorflow. My priorities are Make t...
I have a Python program like this: done = False while u and not done: i = u.pop() print(f"Processing {i}") do_big_task(i) finish_up() Since this takes a long time, the user m...
I would like to use tf.timestamp() when it is available (eager mode and graph mode without XLA), and use 0. (or a better fallback if there is one) when it is not available (with XLA; @tf.function(j...
When running various Python scripts, I often need to do this annoying dance: $ python script.py ... ModuleNotFoundError: No module named 'foo' $ pip install foo $ python script.py ... Module...
I want my CLI Python program to schedule a task, and then exit. After some times has passed (say 10 minutes) the task should execute. The task can be a Python method or a shell command, whatever i...
I am writing a Python package where I have two classes in different files that (indirectly) depend on each other. If I wouldn't care about type-hints, there would be no problem, but unfortunately,...
Is it possible for a Python program to send itself in the background? For example, on Linux you can do nohup some_cmd & and any program will run in the background. Some programs also support s...
I have the following xarray Dataset: d: <xarray.Dataset> Dimensions: (x: 79, y: 63, t: 1) Coordinates: * x (x) float64 0.9412 1.882 2.824 3.765 ... 71.53 72.47 73.41 74.35 * ...
In Python, multiprocessing is easy to do if you follow a "list projection" paradigm. Say you want to take a list of inputs X and apply some function f to every x_i, such that y_i = f(x_i) and the y...
Suppose I have some variables like: >>> count = 8 >>> status = 'off' I want to combine them with some hard-coded text, to get a single string like 'I have 8 cans of Spam®; b...
I know that I can display a single string in the terminal window like print("example") (or similarly with a string in a variable), and I know how to open text files and write to them. I also know ...
Suppose I have two variables that are called animal and age, and print them as a string in the console like so: animal = "giraffe" age = 25 print("A %s can live up to %d years" %(animal,age)) ...
Problem How can I compress each column of a dataframe to the output of a function (i.e., mean), preserving columns? MWE import pandas as pd data = {"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]} ...
I have a function that loads JSON data and is declared to return a dictionary with string keys and values of any type (Dict[str, Any]). However, mypy is raising an error stating that I am returning...
Is there a way to add support for "move symbol" in Python code for VS Codium? PyCharm can do this, but I am looking for a VSC solution. PyLance can do this, but PyLance itself is closed source, a...
In the last few months, AI has advanced considerably, notably in the area of generating images. We now have powerful models like DALL-E, Stable Diffusion, etc. These are quite competent at generati...
I am working on adding uncertainty to some of my dynamics within a larger Monte Carlo simulation. As a way to perform multiple operations on each value, I decided to make and use a new function to ...
I'm experiencing an issue where my program appears to freeze when executing the post_comments_to_lemmy function. This function fetches comments from the GitHub API and posts them to a Lemmy instanc...
I want a way to make it so that I can use list B to find out if a copy of itself exists in list A. listA = ['1', '1', '0', '1', '0', '1', 'down'] 2 ['0', '0', '1', '1', '1', '1', 'up'] 2 ['1', '...
Question What is the current state of the art database app? How does it compare to SQL? Can pandas be used in place of either? If not, is there something that bridges the gap between SQL and pand...
I have a dataset of car bookings like this: car_id user_id 1 1 2 1 1 2 3 3 1 2 3 3 In this dataset, two separate groups/sets of cars and users...
I have a dataset showing electrical current and resistance measurements on various cells of different dies. There are multiple measurements for each cell. If a cell is ever observed to have resist...
When I run pip install foo, pip looks for foo in PyPi. I want it to look for it first in a private repo, let's say pypi.bar.com. Only if foo cannot be found in pypi.bar.com, should pip then look f...
When I set up my object mappings with SQLalchemy, everything works well enough. It even creates the tables for me if they don't exist. However, if I decide to add/remove columns (aka fields) from ...
I'm trying to subclass pdb to have a debugger that, in case of a call to a decorated function, can "step in" the decorated function directly and skip the decorator content altogether. A well-behave...
Here's a JSON log formatter for Python. I want to be able to log details of exceptions (and have some capability to debug-by-logs). I want to be able to log extra data in JSON format (in addition...
Using parentheses in Javascript is always needed when you want to create functions, if/else statements and for/while loops. But in Python it has a function that is called tuples. When using an if s...
The dictionary methods .keys(), .values(), and .items() all return view objects. Said objects reflect any changes to the underlying dictionary. This is often useful. Is there a way to get such a v...
Hello everyone, I am seeking help with understanding why multithreading does not work correctly in this example: import time import matplotlib.pyplot as plt import concurrent.futures voltage...
I have written a screensaver program that, in part, uses the current wallpaper for some visual effects. However, finding the current wallpaper in different operating systems and environments is les...
I started adding types to my (working) solution to Exercism's "Kindergarten Garden" exercise, to learn how typing with python and Mypy (strict) works. While doing so, I ran into a Mypy error that I...
Background The coefficient of variation is: defined as the ratio of the standard deviation to the mean Question Is there a built-in function for this? Tried I know I can do df.std() / df...
MWE filename = "bad_dir" print(f"File not found: {filename}.") raise(FileNotFoundError) Question How do I raise an exception while adding additional information? In the example above, the...
There's this new challenge on Code Golf CD and I'm using Python to do it. A little bit of golfing already took place, so the code might look a bit messy for you. Anyway, I'm proud of what I've writ...
MWE import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(9, 4), columns=['a', 'b', 'c', 'd']) df.plot.bar(table=True) # don't want plot, ...
What exactly is the Python Global Interpreter Lock (GIL)? As someone who is relatively new to Python, is this something I need to be aware of, or is this just some implementation detail of the inte...
MWE import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(9, 4), columns=['a', 'b', 'c', 'd']) df.plot.bar() plt.show() Question Ho...
class ExtendUserSession(MiddlewareMixin): """ Extend authenticated user's sessions so they don't have to log back in following 15 minutes (set by Django's default `SESSION_COOKIE_A...
I've written the following code implementing a state machine in Python, and I'd like some feedback on it. The basic idea is that each state has a set of corresponding actions that trigger a state ...
Having recently learned about protocols in Python, I now wonder if you can write a protocol for enumerations. That is, a protocol that says that you are supposed to pass an enum that has certain it...
In Python 2, I was able to create a file named .env within a project folder like so: # .env MY_ID=abc123 TOKEN=4567890 Then in a Python file in the same directory, I could read these variable...
I have console scripts in my virtual environment in \env\Scripts, installed with packages (e.g. black, pytest, coverage). If I try to execute these in Git Bash, the output is not returned to the te...
The problem Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets are closed by ...
I've written a class that allows to access dictionary entries of arbitrary dicts with appropriate string keys through attribute access syntax on an instance of the class. My questions are: Is...
I have two tables: Table1: Name Description Amount 123 Description123 123 456 Description456 456 789 Description789 666 101 Description777 101 133 De...
The problem You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All t...