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
-3 votes
1 answer
66 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 ...
0 votes
1 answer
3k 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 ...
0 votes
2 answers
88 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: ...
  • 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 ...
-1 votes
2 answers
194 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: ...
-1 votes
1 answer
102 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 ...
1 vote
6 answers
530 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 ...
0 votes
3 answers
131 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 ...
0 votes
1 answer
183 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. ...
  • 11
0 votes
3 answers
469 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[...
  • 109
0 votes
1 answer
1k 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 ...
  • 109
9 votes
4 answers
1k 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 ...
1 vote
3 answers
172 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 ...
-1 votes
1 answer
225 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 ...
4 votes
1 answer
178 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 ...
2 votes
3 answers
440 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 ...
  • 311
1 vote
2 answers
139 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)...
  • 311
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 ...
  • 149
2 votes
2 answers
157 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 ...
  • 149
2 votes
3 answers
422 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 ...
  • 155
-3 votes
1 answer
78 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 ...
  • 213
3 votes
2 answers
398 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 ...
  • 614
1 vote
1 answer
88 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): ...
0 votes
2 answers
1k 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 ...
3 votes
1 answer
97 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 ...
  • 41
-1 votes
1 answer
733 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 ...
  • 115
1 vote
2 answers
97 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. ...
-3 votes
1 answer
51 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. ...
  • 1
5 votes
2 answers
1k 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 ...
  • 388
2 votes
4 answers
191 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(...
0 votes
1 answer
566 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: ...
  • 109
0 votes
1 answer
70 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 ...
  • 101
-1 votes
1 answer
276 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(...
  • 334
3 votes
1 answer
346 views

Best Practice for Populating Objects in Python

So I am pulling data (list of JSON) from an API and want to parse it into Python objects. However the JSON objects of my list returned from my API need to be transformed a bit to fit into my object. I ...
3 votes
2 answers
188 views

Accessing properties from embedded objects as attributes of container class

In Python, I have a class C which embeds objects from classes A and B. Is it considered good practice to creates shortcuts from the properties of embedded objects of classes A and B as attributes of ...
37 votes
13 answers
8k views

Are database unique indexes a mask on bad scripting?

I am working with a coworker on a project that uses Inductive Automation software. If you don't know what it is, all you need to know is it provides a drag-and-drop GUI designer (based in java swing) ...
4 votes
2 answers
1k views

Should I use a namedtuple or dictionary to store immutable values?

I have a code that reads a YAML file that consists of several parameters whose values are used throughout the code. For clarity, the YAML file has the following structure: PARAM_1: value_1 PARAM_2: ...
  • 388
0 votes
2 answers
235 views

fastest way to find number of smaller elements to the right of an array

In Daily Coding Problem, Miller&Wu have the following problem : Given an array of integers, return a new array where each element in the new array is number of smaller elements to the right of ...
  • 181
0 votes
3 answers
334 views

Should I unit test functions internally used by API I expose?

I'm writing a CRUD app in Python that exposes web API. At first I wrote functions for communicating with DB and wrote tests for these functions. def crud(): # do something with db def test_crud(): ...
11 votes
6 answers
3k views

Is ad-hoc polymorphism a good practice in functional programming?

I am developing a utils data engineering package in python, and for the sake of reusability and readability, I chose the functional programming (FP) approach. Assume a key task of converting data from ...
  • 221
3 votes
1 answer
931 views

Duplicate code for imports Python

In a project I have the same imports in multiple files. For example: import os import logging import json import time import pathlib and pylint will tell me I have duplicate code. I know that there ...
  • 149
1 vote
2 answers
145 views

Is nesting try-except sequence in try-else block bad form?

Ive got a boot sequence that needs to check some registry values, they may or may not be present, so each check needs to be wrapped in its own try-except. I try to avoid nesting as I think it can lead ...
  • 1,017
-1 votes
1 answer
159 views

Conversion methods: from_xxx() or to_xxx(), is there a reason I shouldn't stick with to_xxx()?

I have a C++ library that I'm converting to Python. In the C++ library I have multiple constructors and many different types of conversion functions (think radians to degrees, and different types of ...
  • 1,232
0 votes
0 answers
93 views

Trade-off between usability and clean design

I have designed our in-house hardware testing framework. My goal is to ultimately release the framework into the public domain. Early on, my foremost design criterion was to provide a powerful yet ...
1 vote
1 answer
586 views

Should I check floating point values in a unit test?

We have unit tests that are running some underlying model. We provide it with some test input, and receive some outputs + floating point scores. What's a good practice from a unit-testing standpoint? ...
  • 155
0 votes
1 answer
901 views

When should I use a global variable module in Python?

In Python projects, if your project spans multiple Python modules and you need to pass some data between the modules, as far as I know, there's 2 main ways: Pass the data as function arguments Create ...
  • 111
-3 votes
1 answer
61 views

Creating a Django web-app with Sage 200 Database

I have been asked to create a Django/Python web app that creates web-based, .pdf and excel reports from a Sage Evolution database. While the sage front-end is still being used. My client essentially ...
  • 1
11 votes
6 answers
6k views

Is it reasonable to use dictionaries instead of arguments?

In python I often see functions with a lot of arguments. For example: def translate(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p): // some code return(x, y, z) I like this pattern in some ...
1 vote
1 answer
144 views

Purpose of a method prefaced by __ underscores when no subclasses present

I'm trying to understand why it is appropriate to have a method prefaced by __ underscores when no subclasses are present. There are thus technically no naming conflicts that could arise. I'm ...
0 votes
1 answer
929 views

Type-hinting and accessing values that are not initialized in __init__ (Python)

Suppose I have an instance attribute that I don't initialize in __init__, but in normal use it should be initialized before any other methods use the value. I want to structure everything so that it ...
  • 119

1 2
3
4 5
39