Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

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

20 child tags

Use for questions about the Python programming language. Python is a multi-paradigm, dynamically typed, multipurpose programming language.

Consider adding a major version tag such as [python-2.7] or [python-3.x] when this is relevant for the question.

This tag doesn't have a detailed wiki yet.

66%
+2 −0
Q&A How and where does Python code start running? How can I control that?

Suppose I have some code in a file myscript.py like: def my_function(): print("Test") What steps do I need to take in order to make my_function run? That is to say: how do I get Python to ...

1 answer  ·  posted 3d ago by Karl Knechtel‭  ·  last activity 3d ago by Karl Knechtel‭

50%
+0 −0
Q&A How to merge Django model query results?

I have to modify a legacy Django web application where there are 2 tables to store the same information using the same database structure, and the only difference is the names of the tables (and th...

1 answer  ·  posted 10d ago by toraritte‭  ·  last activity 10d ago by toraritte‭

71%
+3 −0
Q&A Privilege escalation from Python like from systemd

When you try to do a privileged systemd operation without the privilege, you get an escalation prompt: $ systemctl stop docker ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ==== ...

1 answer  ·  posted 13d ago by matthewsnyder‭  ·  last activity 13d ago by Karl Knechtel‭

50%
+2 −2
Q&A How to group a flat list of attributes into a nested lists?

I have a flat list where each item is the key and value for an attribute. I want to transform this into a nested list where each attribute is a sublist. Example input: [ "attr1 apple 1", "a...

2 answers  ·  posted 1mo ago by aditya98‭  ·  last activity 1mo ago by matthewsnyder‭

Question python grouping list
75%
+7 −1
Q&A How can I provide additional information when raising an exception?

Suppose I have some code like: filename = "bad_dir" print(f"File not found: {filename}.") raise(FileNotFoundError) When the exception isn't caught, the stack trace is printed at the end of ...

2 answers  ·  posted 1y ago by mcp‭  ·  edited 3mo ago by Karl Knechtel‭

Question python exception
84%
+9 −0
Q&A Open file in script's own folder

I have a Python script that needs to access some data (or configuration) file in its very own folder. For example, say script.py does something like this: with open('data.txt') as file: data ...

2 answers  ·  posted 2y ago by J-hen‭  ·  last activity 3mo ago by Karl Knechtel‭

81%
+7 −0
Code Reviews Detecting balanced parentheses in Python

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 ...

5 answers  ·  posted 3y ago by Vinicius Brasil‭  ·  last activity 3mo ago by Dirk Herrmann‭

Question python
80%
+6 −0
Code Reviews JSON log formatter

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...

2 answers  ·  posted 12mo ago by misk94555‭  ·  last activity 3mo ago by Karl Knechtel‭

Question python logging
71%
+3 −0
Q&A PEP20 on namespaces: What exactly is it saying to do?

PEP20 aka the Zen of Python has a statement: Namespaces are one honking great idea -- let's do more of those! What exactly are we supposed to "do" according to this? Is it saying we should h...

0 answers  ·  posted 5mo ago by matthewsnyder‭  ·  edited 5mo ago by Karl Knechtel‭

66%
+4 −1
Q&A Does Python have a "ternary operator" (conditional evaluation operator like "?:" in other languages)?

Sometimes code needs to assign (or otherwise use) a value that depends on some condition. The naive approach is to use explicit branching, which in Python would look like: if some_condition(): ...

2 answers  ·  posted 5mo ago by Karl Knechtel‭  ·  last activity 5mo ago by matthewsnyder‭

Question python syntax
84%
+9 −0
Q&A Understanding mutable default arguments in 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 ...

4 answers  ·  posted 7mo ago by Karl Knechtel‭  ·  last activity 5mo ago by matthewsnyder‭

88%
+14 −0
Q&A Why are list comprehensions written differently if you use `else`?

The following list comprehension worked when I tried it: [num for num in hand if num != 11] But this doesn't work: [num for num in hand if num != 11 else 22] It gives a SyntaxError, highlightin...

2 answers  ·  posted 2y ago by true_blue‭  ·  last activity 5mo ago by Karl Knechtel‭

66%
+2 −0
Q&A Get list of all variables from Jinja template

Suppose you have a jinja template like this: I am going to {{ foo }} to get some {{ bar }}. I hope I can find: {% for i in baz %} - {{i}} {% endfor %} This template will require you to pass ...

0 answers  ·  posted 6mo ago by matthewsnyder‭  ·  edited 6mo ago by Karl Knechtel‭

71%
+3 −0
Q&A Can you run Python code on text in VS Code?

In VS Code, is it possible to run Python code on the text being edited? I realize that I can save my text, create a .py file, switch to a terminal (including VS Code's own terminal) and run the .p...

0 answers  ·  posted 7mo ago by matthewsnyder‭

66%
+2 −0
Q&A Remove entries by two-column ID everywhere, that meet a condition somewhere

MWE import random import pandas as pd from itertools import product random.seed(12345) dies = [1, 2] cells = list(range(10)) currents = [100, 200, 300] dcc = list(product(dies, ce...

3 answers  ·  posted 1y ago by mcp‭  ·  edited 7mo ago by mcp‭

50%
+1 −1
Q&A Is there a text version of pickle?

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...

0 answers  ·  posted 7mo ago by matthewsnyder‭

50%
+0 −0
Q&A Best practices to write functions for both execution modes in Tensorflow, eager and graph mode

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....

1 answer  ·  posted 8mo ago by daniel_s‭  ·  edited 8mo ago by daniel_s‭

66%
+2 −0
Q&A Is it okay to use python operators for tensorflow tensors?

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...

1 answer  ·  posted 8mo ago by daniel_s‭  ·  edited 8mo ago by meta user‭

60%
+1 −0
Q&A Can't use tf.timestamp() from within @tf.function with XLA / jit_compile=True

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...

0 answers  ·  posted 8mo ago by daniel_s‭

77%
+5 −0
Q&A How can I schedule a later task in Python?

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...

3 answers  ·  posted 8mo ago by matthewsnyder‭  ·  last activity 8mo ago by H_H‭

77%
+5 −0
Q&A How can I properly type-hint methods in different files that would lead to circular imports?

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,...

2 answers  ·  posted 8mo ago by mr Tsjolder‭  ·  edited 8mo ago by Alexei‭

71%
+3 −0
Q&A How can a Python program send itself to the background?

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...

1 answer  ·  posted 8mo ago by matthewsnyder‭  ·  last activity 8mo ago by r~~‭

50%
+1 −1
Q&A How to resolve a "ValueError: dimension 't' already exists as a scalar variable" arising when I am using xarray.Dataset.assign_coords()?

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 * ...

1 answer  ·  posted 8mo ago by Ivan Nepomnyashchikh‭  ·  last activity 8mo ago by mr Tsjolder‭

Question python xarray
66%
+4 −1
Q&A How can I build a string from smaller pieces?

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...

2 answers  ·  posted 9mo ago by Karl Knechtel‭  ·  last activity 9mo ago by Karl Knechtel‭

71%
+3 −0
Q&A How can I output / display multiple values, with controlled spacing, without building a string?

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 ...

1 answer  ·  posted 9mo ago by Karl Knechtel‭  ·  last activity 9mo ago by Karl Knechtel‭

Question python format output
61%
+6 −3
Q&A Why are commas not needed for modulo string formatting when printing?

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)) ...

3 answers  ·  posted 1y ago by Bennshinpoes‭  ·  edited 9mo ago by Karl Knechtel‭

71%
+3 −0
Q&A How to compress columns of dataframe by function

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]} ...

2 answers  ·  posted 1y ago by mcp‭  ·  last activity 9mo ago by mr Tsjolder‭

Question python pandas
71%
+3 −0
Q&A How to resolve the mypy error "Returning Any from function declared to return 'Dict[str, Any]'" in Python?

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...

1 answer  ·  posted 9mo ago by ShadowsRanger‭  ·  last activity 9mo ago by Moshi‭

Question python mypy
66%
+2 −0
Q&A "Move symbol" refactor for Python in Visual Studio Codium

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...

0 answers  ·  posted 9mo ago by matthewsnyder‭  ·  edited 9mo ago by matthewsnyder‭

50%
+2 −2
Q&A Slicing a dictionary using a string variable

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 ...

1 answer  ·  posted 9mo ago by megalomaniac‭  ·  edited 9mo ago by megalomaniac‭

Question python
42%
+1 −2
Q&A Program freezing in `post_comments_to_lemmy` function due to potential infinite loop

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...

1 answer  ·  posted 9mo ago by ShadowsRanger‭  ·  last activity 9mo ago by __blackjack__‭

Question python
20%
+0 −6
Q&A how to use one list to find a similar list in another list python

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', '...

1 answer  ·  posted 1y ago by Solaranfel1366‭  ·  last activity 10mo ago by Alias Cartellano‭

Question python list
57%
+2 −1
Q&A Can pandas be used as a database backend for persistent storage?

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...

2 answers  ·  posted 10mo ago by mcp‭  ·  last activity 10mo ago by matthewsnyder‭

71%
+3 −0
Q&A Is it possible to get the current function in a trace function?

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...

1 answer  ·  posted 12mo ago by luser‭  ·  last activity 12mo ago by r~~‭

Question python debugging
57%
+6 −4
Q&A Why can parentheses cause exceptions in Python when using for loops?

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...

1 answer  ·  posted 1y ago by Bennshinpoes‭  ·  edited 1y ago by trichoplax‭

Question python syntax-error
71%
+3 −0
Q&A How do I get something similar to dictionary views, but for sequences?

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...

1 answer  ·  posted 1y ago by ajv‭  ·  last activity 1y ago by r~~‭

Question python python-3
71%
+3 −0
Q&A Python Parallel plotting and and input reading

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...

1 answer  ·  posted 1y ago by kek‭  ·  edited 1y ago by kek‭

75%
+4 −0
Q&A What's causing mypy to give an `[assignment]` error in this nested for loop?

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...

2 answers  ·  posted 1y ago by true_blue‭  ·  last activity 1y ago by Moshi‭

Question python mypy
28%
+0 −3
Q&A Built-in way to compute coefficient of variation in pandas

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...

1 answer  ·  posted 1y ago by mcp‭  ·  last activity 1y ago by cuzzo‭

Question python pandas
45%
+3 −4
Q&A Create a list of Niven numbers in Python

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...

2 answers  ·  posted 1y ago by General Sebast1an‭  ·  last activity 1y ago by Dirk Herrmann‭

Question python function
66%
+2 −0
Q&A How to plot table from pandas dataframe

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, ...

1 answer  ·  posted 2y ago by mcp‭  ·  last activity 1y ago by __blackjack__‭

77%
+5 −0
Q&A What is the Python Global Interpreter Lock?

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...

1 answer  ·  posted 1y ago by Moshi‭  ·  last activity 1y ago by Derek Elkins‭

Question python python-gil
71%
+3 −0
Q&A How to add vertical lines for visual separation in pandas plot

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...

2 answers  ·  posted 2y ago by mcp‭  ·  last activity 2y ago by samcarter‭

28%
+0 −3
Q&A Need help in migrating a Python2 custom middleware to current Python3 version

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...

0 answers  ·  posted 2y ago by roronoa_zoroDR‭  ·  last activity 2y ago by Monica Cellio‭

Question python django-drf
66%
+4 −1
Q&A Load environment variables from .env file in Python 3 [closed]

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...

0 answers  ·  posted 2y ago by qohelet‭  ·  closed 2y ago by Alexei‭

81%
+7 −0
Q&A Console scripts in virtual environment do not output to terminal in git bash

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...

1 answer  ·  posted 2y ago by boudewijn21‭  ·  last activity 2y ago by boudewijn21‭

71%
+3 −0
Code Reviews A class to access dicts using attribute syntax

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...

2 answers  ·  posted 2y ago by celtschk‭  ·  last activity 2y ago by luser‭

Question python hashmap
62%
+3 −1
Q&A Comparing two excel files with Python based on changes

I have two tables: Table1: Name Description Amount 123 Description123 123 456 Description456 456 789 Description789 666 101 Description777 101 133 De...

1 answer  ·  posted 2y ago by sfrow‭  ·  last activity 2y ago by ibmx‭

Question python pandas
77%
+5 −0
Code Reviews Counting Sundays without Python datetime module

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...

1 answer  ·  posted 3y ago by Vinicius Brasil‭  ·  edited 2y ago by hkotsubo‭

Question python date
71%
+3 −0
Q&A Docutils rst2pseudoxml.py reported error: No role entry for "meth"

docutils's rst2pseudoxml.py is reporting this error: Unknown interpreted text role "meth". even though the build command: sphinx-build -b html -d build/doctrees source build/html runs fine and pro...

1 answer  ·  posted 2y ago by CodeFarmer‭  ·  last activity 2y ago by J-hen‭