Questions tagged [python]

Python is a dynamically typed, high-level interpreted programming language. Its design focuses on clear syntax, an intuitive approach to object-oriented programming, and making the right way to do things obvious. Python supports modules and exceptions, and has an extensive standard module library. Python is general-purpose and thus used widely, from the web to embedded systems.

Filter by
Sorted by
Tagged with
0 votes
1 answer
30 views

PyPI Package Names Governance

The Python Package Index (PyPI) is a public repository, and it seems that anyone can upload packages to it using a tool like twine. The openness of the system raises some questions: Say, a person/...
user avatar
  • 123
0 votes
0 answers
25 views

Alternative design pattern to a method containing a lot of methods? [duplicate]

I have a method in a class that takes in some variables and then runs a series of other methods in a pre-defined sequence. Below is a simplistic example: class MyClass: def ...
user avatar
  • 281
-1 votes
1 answer
27 views

How to handle config/env vars in a library project

I am building a new Python library project to be consumed by several of my application projects. The existing code consumes environment variables for various configuration settings. Should my ...
user avatar
  • 153
3 votes
1 answer
138 views

Why does CPython has both C and .python versions of modules?

The CPython implementation seems to have the same modules written both in C (e.g., datetime in .c) and also in .py for the same module (e.g., datetime in .py). My question is which version is used ...
user avatar
-1 votes
1 answer
39 views

Best practices for naming python utils / extending core modules?

So a lot of the time my utils end up with a structure that mirrors the core library. I might end up writing a multiline version of str.center, an itertools-y function that returns the first or last ...
user avatar
  • 11
1 vote
2 answers
118 views

What is a good way to call a unit-tested function provided by a library/package?

Consider the function foo provided by package X in Python. I want to test the different functionalities of X.foo, and then use X.foo in my code. To make sure that I am using X.foo as it was tested, I ...
user avatar
  • 121
1 vote
1 answer
158 views

Properly "exposing" a variable from a class in Python

I have a Launcher class that manages (check if they're alive and if not respawns them, also starts, etc.) Clusters which are processes launched through the multiprocessing Discord module. To post ...
user avatar
  • 121
0 votes
2 answers
91 views

TL suggests that testing, refactor, and tool usage could avoid the need for verbose logging

Additional Context I make infrastructure for automated device testing. Debugging can be very time consuming because the devices have many states and are constantly being updated with new builds which ...
user avatar
  • 1,655
0 votes
1 answer
42 views

How to properly isolate tests for dataframes with grouping?

I have the following problem: I would like to test complex business logic for each test case completely separately, i.e. all tests should run in parallel. I don't want the test for customer #43 to ...
user avatar
-1 votes
1 answer
50 views

How to use lazy import to speed up a list of known types in python? [closed]

I have an application in which the user can describe an analysis job via a yaml like analysis: learner: name: LinearRegression args: solver: liblinear and then it is parsed to ...
user avatar
-5 votes
1 answer
54 views

Python - Brainstorming: How would you compare texts and find differences? [closed]

In the beginning, I would like to state that this is not meant to be a discussion. But I would like to receive only suggestions for possible solutions or, at least, a comment on my proposed solution: ...
user avatar
0 votes
0 answers
41 views

gRPC streaming proxy | Architectural decision

I'm building microservices app that supposed to launch tests in separate containers. I also want to stream log messages to frontend and store them in database and I don't know what solution would be ...
user avatar
-1 votes
1 answer
42 views

Are there different ways in Python to decorate class methods that dynamically assign themselves to a dict within the class?

Here's what I'd like to do in the form of working code, since it's difficult for me to explain otherwise: from typing import Callable, Generic, TypeVar from typing_extensions import Self # The type ...
user avatar
0 votes
0 answers
31 views

Optimizing database lookup with No SQL MongoDB

My restraints are that I have to use: Django and MongoDB I am trying to build a website that will read some JSON input and then parse all the properties and objects in the JSON and display results. ...
user avatar
  • 1
0 votes
1 answer
92 views

Correct way to deduplicate conditional statements [closed]

I'm facing with problem that in every function (with serves as service for endpoint) I need to check what is value of query parameter (mode). I need to check it on many callables, E.g. def create(self,...
user avatar
  • 111
-3 votes
1 answer
20 views

Adding rows and columns simultaneously to pandas dataframe

I am new to Python (~ 1 month) and am having a hard time figuring out a clean, fast way to simultaneously append rows and columns to a dataframe automatically. As a representative example, I will ...
user avatar
1 vote
1 answer
212 views

Is it considered as bad practice to have code on the __init__.py? [closed]

I am a bit confused about best practices when it comes to where and how to initiate the Flask() or FastAPI() for a data-intensive web API. The vast majority of the code available online is using this ...
user avatar
0 votes
2 answers
57 views

Design Review: Queuing tasks to add rows of data followed by task to send email

I need to send personalized emails to a filtered set of users (~100,000) on every fortnight. I am using Marketing cloud API for it. The way I am thinking of designing the system is as follows: ...
user avatar
  • 101
12 votes
3 answers
2k views

Should I choose repeated code in unit test or test logic? Can I avoid both?

When writing unit tests, I feel that there is a trade-off between code repetition and test logic. Example of my current (likely flawed) approach: To test this function (overly simple function for ...
user avatar
-1 votes
2 answers
178 views

What is the best practice of conditions style in Python?

We have a function that processes the user request if it is not None, how best to style it? I did not find a better choice in PEP8 Style 1 def user_handler(user): if db.getUser(user) is not None: ...
user avatar
-1 votes
1 answer
63 views

How to get rid of multiple if statements in code flow related to different modes/datasets - Python? [closed]

My Python project comprises data handlers, models and can be run with different modes. Throughout my code I use statements like if mode=='mode1': # or if isinstance(model, Model1): To adapt the flow ...
user avatar
1 vote
6 answers
404 views

When to NOT use static code analysis tools?

There are many posts about the benefits of static code analysis tools. However, in which scenarios would you recommend NOT using (or significantly limit) them? For example, do you also run them on ...
user avatar
0 votes
3 answers
110 views

Merging Python2.7 code to its ported Python3.9 version

I am working on a Django based project that is version controlled with SVN. My main objective is porting it from Python2.7 to Python3.9. Whilst I port the project, my team brought some updates, now I ...
user avatar
0 votes
1 answer
55 views

Should I Add Integration Or Unit Tests To Django Views

I am currently exploring adding unit tests to my Django REST Framework project. I totally understand adding unit tests for other components of the app like models. However, I'm stuck at testing views. ...
user avatar
  • 1
0 votes
2 answers
101 views

Python best practice when logging optional arguments

I have a method that accepts one or more optional arguments and I'd like to log them, following the best practice of lazy interpolation of log values: def frobnicate(a: str, b: int, c: typing.Optional[...
user avatar
  • 101
0 votes
1 answer
93 views

Designing a system to hit multiple HTTP requests serially

Hope this is the right StackExchange community to ask this question. I am building a (Python) project that will have a list if URLs to hit. They have to be hit serially, and part of response of one ...
user avatar
  • 109
8 votes
4 answers
950 views

How did Python come to be so popular amongst data scientists? [closed]

I've been curious about why Python seems to be so popular amongst data scientists. Firstly I needed to check there was some truth to this assertion so I wrote a query on the StackExchange data ...
user avatar
1 vote
3 answers
162 views

How to design a function with different output formats

I often have to write a function which may return an output of two kinds: "short" and "long". As an example, consider the subset sum problem: the input is a set of integers S and ...
user avatar
-1 votes
1 answer
106 views

How to write tests for a class that talks to a server without revealing connection implementation

I'm writing a class that acts as the interface to a server. The interface exposes a way to send messages to the server and pass messages back to the client through a callback. Implementations should ...
user avatar
3 votes
1 answer
160 views

How can I create a workflow for physical unit safety in Python?

I work for an engineering firm which builds most of our physics models in Excel with VBA. For myself and many other younger mechanical engineers in the company, this is not a good solution - we grew ...
user avatar
2 votes
3 answers
170 views

Should classes with business logic inherit from a class with helper methods, or vise-versa?

I have a codebase where some classes contain both "essential" business logic, and "incidental" complexity. I am considering a refactor where I leverage inheritance to improve the ...
user avatar
  • 195
1 vote
2 answers
129 views

Should I add functionality by adding a new method to a class - or should I "register" the new functionality into a data structure?

I have one large class that computes ~50 different metrics (each metric has no side effects). My code is similar to this: class ReportingMetrics: def __init__(self, data:pd.DataFrame, config:dict)...
user avatar
  • 195
1 vote
1 answer
34 views

Register a collection of tested object and get one configuraton out of it

I have a yml configuration file that list multiple application. Each application can contain multiple configuration. And of course each configuration can contain multiple mode apps: - name: foo ...
user avatar
  • 149
2 votes
2 answers
134 views

Type checking, multiple functions and how to overcome function parameter names?

I have a search function. This function takes 4 different parameters that can be either a list of strings or a string. For each parameter, if it's a string I convert it to a list of strings. def ...
user avatar
  • 149
2 votes
3 answers
289 views

Still don't understand when to mock and when not to

I've been trying to understand when to mock and when not to mock, however I'm not able to come up with a consistent guideline and I'm hoping to get some input on the subject. Let's look at the ...
user avatar
  • 155
-3 votes
1 answer
63 views

Applying a file diff to a new file [closed]

Suppose I have file a.txt, b.txt and c.txt: a.txt: Hello, I like cake. b.txt: Hello, I like turtles. c.txt: go away, I don't like you I suspect the difference between a.txt and b.txt is ...
user avatar
  • 213
3 votes
2 answers
245 views

Is it good practise to rely on the insertion order of python dicts?

Since python 3.7, it is guaranteed that dictionaries maintain insertion order. The linked stackoverflow Q&A states This simply means that you can depend on it. Is it good practise to depend on ...
user avatar
  • 615
1 vote
1 answer
73 views

Proxy Pattern in Python

I'm reading a book on design patterns. On proxy pattern the code are following: class SensitiveInfo: def __init__(self): self.users = ['nick', 'tom', 'ben', 'mike'] def read(self): ...
user avatar
0 votes
2 answers
204 views

Usage of property decorator for private attributes in classes in Python

I've started learning Python recently, and there are some topics I cannot really understand. One is the usage of the decorators in user defined objects, or encapsulation more generally. I mean, let's ...
user avatar
3 votes
1 answer
87 views

Designing shared subtype functionality with correct type annotations in Python

To illustrate the problem, I'm defining a PositiveNumber class that is a subclass of a Number class. As Python doesn't support type casting, I'm defining the from_number as a convenience method I can ...
user avatar
  • 41
-4 votes
1 answer
58 views

Is there a way to use a third party Python or C API through C#? [closed]

I will receive a hardware which will have native Python API to communicate through USB. The device will continuously send image data. The vendor only supports Python and C APIs to communicate with the ...
user avatar
  • 129
-1 votes
1 answer
136 views

Query language for python dictionary

I have a list of python dictionaries (let's assume each dict is flat for the time being). The keys are all strings and the values are strings or real numbers. I would like the user to have the freedom ...
user avatar
  • 115
1 vote
2 answers
86 views

What do you call a process which transforms objects of complex types into simple objects of primitive types? [closed]

My first thought was that I'm "serializing" the complex object, but from what I understand that means I'm reducing it down to a string or binary format which could be passed over a network. ...
user avatar
-3 votes
1 answer
48 views

Is it possible to add a unique identifier to the shared Data via bittorrent (P2P)?

I know that P2P sharing is copying the exact content between the peers. Everyone has the same data. Let's assume the content is very important and I don't want anyone to distribute outside the group. ...
user avatar
  • 1
5 votes
2 answers
933 views

Design classes to model 3D scanned faces of ancient Greek/Roman sculptures: is multiple inheritance a good design solution?

I would like to deepen the topic of multiple inheritance using Python and I usually find examples that are too simple. I love art and I imagined the following problem and I want to understand if ...
user avatar
  • 358
2 votes
4 answers
187 views

How to refactor a lot of Functions that can be run in two different modes

I have some code and in it there are functions which can be run in one of two modes (in my case server mode and local mode). For example, most functions look something like this: def path_join(...
user avatar
0 votes
0 answers
21 views

DRF API - using Multitable Inheritance vs "profiles"

I'm looking forward to your opinion on how to do this. This is a backend that will be served as a Django Rest Framework API. There will be multiple types of properties. Properties have approximately ...
user avatar
  • 119
0 votes
1 answer
124 views

How to test a function with several conditional nested side effects

In Python, consider a function like the following: def main(*args): value1 = pure_function1(*args) if condition(value1): value = side_effect1(value1) if value: ...
user avatar
  • 109
0 votes
1 answer
40 views

Automatically scheduling CRON jobs via API

So, I'm working on a specific solution that requires the creation of jobs that should run at a specific time, and complete a certain action. We've built a GUI where the client inputs params required ...
user avatar
  • 101
-1 votes
1 answer
128 views

Why is `replace(dataclass, **kwargs)` a function, and not a member?

Imagine a simple data class: @dataclass class Settings: m: int s: str old = Settings(m=10, s="ten") It feels normal to write new = old.replace(m=1), but we have to write new = replace(...
user avatar
  • 334

1
2 3 4 5
38