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
2 answers
380 views

Loop outside method or method with internal loop?

If I have a list of objects that need to have an operation performed on each, is there a best practice in abstracting the loop or not? Looping over list and call def func(item): some_op(item) ...
  • 1,037
6 votes
2 answers
312 views

How do you unit test functions split in smaller functions

The problem is the following, suppose we have this functions: from PIL import Image from magiclibrary import perform_some_operation, stack_images def load_image(path: str): if isfile(path): ...
0 votes
2 answers
324 views

Which is the best data structure to use when you want to randomly pick elements & use them, but also delete them after use

I have 1000 lines in a text file. I want to read them into some data structure[DS]. After reading them, I will be randomly picking 50 lines from the DS (using a Random Number Generator). Next time 50 ...
  • 441
1 vote
1 answer
1k views

Using isinstance() during exception handling for subsequent action

I've read various posts that polymorphism should be used instead of isinstance, and I agree that makes sense when the use of isinstance is checking the subtypes of a class to determine what to do. ...
  • 1,037
0 votes
1 answer
89 views

Design suggestions for my simple data-analysis program

I need to create a program with the purpose of cross-referencing personal info from a spreadsheet(s), to check for conflicts of interest between clients of 3 different law firms. All of this client ...
  • 109
0 votes
0 answers
57 views

Python: signals-based high performance communication system

I am working on a python framework for building a special kind of editors (so they have GUI) and I just split it into backend and a frontend (distinct libraries), s.t. another frontend could be ...
  • 11
3 votes
4 answers
293 views

Python access properties via public or private interface?

I work with Python classes that define properties that return some privately managed data member. When accessing this data in the body of other methods, is it better practice to use the public or ...
1 vote
1 answer
90 views

Improvement of the config file management

I am working on a personal project for more than 6 months now, this project is composed of three distinct parts, simulation (wrapping a software), database related stuff (store the simulated data in a ...
  • 13
0 votes
1 answer
250 views

Python: Function pipeline with multiple return/input values, or use OOP? Best Practices?

I have a 'processing' function and a 'serializing' function. Currently the processor returns 4 different types of data structures to be serialized in different ways. Looking for the best practise on ...
3 votes
1 answer
756 views

Handling same exception thrown by different methods

Is there an idiomatic way to catch an exception when multiple methods may throw?: try: someMethod() # raises OSError someOtherMethod() # raises OSError except OSError: handle() The ...
  • 1,037
4 votes
1 answer
736 views

How do you perform accumulation on large data sets and pass the results as a response to REST API?

I have around 125 million event records on s3. The s3 bucket structure is: year/month/day/hour/*. Inside each hour directory, we have files for every minute. A typical filename looks like this: ...
  • 51
0 votes
1 answer
705 views

Is it better to pass self or the specific attributes in Python methods?

I'm trying to understand when it is better to pass explicit arguments to a method and when it is better to just pass self. I created a little example to illustrate the question. Here are two different ...
  • 253
1 vote
1 answer
232 views

Is bytes as request parameters as rest endpoint a security risk?

I am working on an application where user can send in an absolute path of an image or URL as string in API endpoint. My code is able to handle that. Now I have been asked to add the code which can ...
2 votes
2 answers
2k views

Alternative to using regex in Python

Background I do programming with Python and now and then i run into a situation where i have to use regex Typically i try to learn a bit about it and look at examples of doing things similar to what i'...
  • 439
0 votes
1 answer
80 views

Recommended way to use a python backend from a c#-application

I have an old windows forms gui used to control a custom measurement system. Originally, it handled acquisition, calculating, database handling and presentation of measurements. Now, because of some ...
  • 3
-2 votes
1 answer
292 views

Best practice: keep DB models in one file or split into modules?

I've a Python project with ~30 SQLAlchemy models and I'm not sure where they belong. All models belong to the DB but also to a module, so I'm not sure about the right namespace. Here are some ideas: ...
  • 143
31 votes
10 answers
7k views

What is a good approach to handling exceptions?

I have trouble reconciling "best practices" and real-world approaches to handling exceptions. In my day to day routine, I find myself running into the following examples: try: ...
  • 465
6 votes
3 answers
1k views

Is there a better way to run sequential tests?

I'm using unittest framework to run Python tests. Some system tests consist of a series of steps for a given scenario, and they need to run in a specific order. For example, I have a client ...
-1 votes
1 answer
661 views

Python generating payload and parsing payload

(Using python) I am looking to generate a bytes (or can be string that I convert to bytes) that is a message to send over TCP. The format is [Header][Length][Payload]. Within [Header] is a [...
  • 191
1 vote
0 answers
68 views

What's the best way to build a Flask API to control and show the status of a program tool I have built?

I've developed a backend project using Python. It collects data from different sources, process the data, and then perform actions with it (for example, store relevant info in a database). To execute ...
  • 11
0 votes
1 answer
63 views

Best way to migrate to new versions of librairies with breaking changes

(I orignally posted my question on StackOverflow and figured maybe this would be a better place to ask) I provide details on the librairies I'm working with because it helps understand my issue but it ...
-2 votes
1 answer
629 views

Good idea to use source control with my Lambda functions?

So, I have this legacy project I am starting to hump into with my team. This is a AWS Lambda Python application (a bunch of Micro-services that inform various front-ends). So, when I asked how they ...
1 vote
0 answers
56 views

Securing Arbitrary Code

I need to run arbitrary code snippets in Python and Javascript on a server. It cannot be run in the browser. I'm thinking of sandboxing the code in an AWS Lambda serveless function. However, I'm ...
0 votes
2 answers
91 views

What is best practice for getting a variable passed into a function several layers deep in a local function call?

I have a situation as follows, I have a relative path that I want to get for a directory. The directory structure is as follows, Windows Folder Structure C:\FileFolder\LowerLevel\ThirdLevel\script.py ...
2 votes
3 answers
194 views

How can I avoid chasing my own tail when testing against complicated return values?

Sometimes there are functions that return complicated data and cannot be divided any further e.g. in the area of signal processing or when reading and decoding a bytestring to another format. How am I ...
  • 23
0 votes
3 answers
269 views

Is it really good practice in Python code for machine learning to use so many parameters?

Currently I am a student learning Machine Learning, and so my observation is from an academic context. It may be different in a business environment. One thing I find very odd when I see Python code ...
  • 125
4 votes
3 answers
468 views

Inheritance vs composition: How would you implement an "unordered list"? Subclass of list, or composition?

This came up at work and left me thinking about the best way to model this: In Python, we have the built-in list container, which is a mutable sequence. Equality between two lists is defined as ...
  • 516
2 votes
1 answer
605 views

Best approach for developing a stateful computation-heavy application with a rest-api interface using python?

I want to develop an end-to-end machine learning application where data will be in GPU-memory and computations will run on the GPU. A stateless RESTfull service with a database is not desirable since ...
6 votes
1 answer
831 views

Why would it be considered bad practice if a concrete class inherits from only one Mixin?

I'm referring to "Fluent Python" by Luciano Ramalho. In chapter 12, there's a section "Coping with Multiple Inheritance" where the author suggests a few best practices, such as: ...
  • 516
1 vote
0 answers
227 views

How to isolate a Python script/plugin from the main Python program?

I want to have a Python application - complete in itself - that allows the user to extend it via scripting (or a plugin model) in Python. But I want the script/plugin to have an isolated environment (...
  • 682
5 votes
3 answers
11k views

Is it a good practice to use logging inside classes/functions in Python?

So far, I've been using logging only in main() mostly. I do not log anything in my functions or classes but sometimes I feel like it would be helpful. What I would do now: def init_logger(): # ...
  • 205
5 votes
4 answers
478 views

Processing a 2D matrix - need to speed up my O(n^4) algorithm

I have an n x n matrix which I need to convert into a list sorted by value. Starting with the maximum value cell at (row x1, col y1), I must immediately exclude all cells where (x >= x1, y <= y1)...
  • 187
1 vote
1 answer
435 views

Easiest way to build and distribute Excel UDF add-in capable of Statistical Analysis

01 - BACKGROUND: I'm a typical non-programmer R user for 6+ years. Which means: i) I`m comfortable with the language most of the time and have written R packages for myself, but ii) writing C++ code (...
  • 27
3 votes
3 answers
261 views

Indexable iterators

Suppose someone designs an indexable iterator class, i.e. an iterator that supports __getitem__ for (non-negative) integer indexes such as the following: In [1] it = indexed_iter("abcdefghij"...
  • 403
0 votes
2 answers
318 views

What if integration testing makes more sense than unit testing for a certain method?

I don't want to spam you with a ton of code, but please have a quick look at this boiler-plate method: In this scenario let's say I have a ProcessingText.py file (class) that I finished its unit ...
-4 votes
1 answer
189 views

Import chains in Python

If my foo.py is merely foo_var = 1 and bar.py is merely import foo, I know I can write baz.py that says from bar import foo_var, but should I? (Or should I instead do from foo import foo_var?) Is ...
  • 667
-2 votes
1 answer
83 views

What should I use to graphically represent an object's position on a fixed path using python(preferred)?

Consider 2 roads merging into one(This map is supposed to remain fixed). The program will not generate this map. The program will read this map and plot positions on it on its own. The python program ...
  • 9
1 vote
0 answers
40 views

Is there a simpler way to monitor changes to a piece of data, and disallow removing the data from monitoring?

I'm working on an algorithm visualizer for sorting algorithms. Give it a (user-submitted) sorting algorithm, hit run, it'll generate a random list of integers and show you what the algorithm looks ...
  • 141
1 vote
3 answers
869 views

Using python context managers instead of passing arguments: Is it an anti pattern?

We have an input flag in our API which indicates whether we should keep the mid level resources involved in fulfilling current request or not. I've decided to use some context managers at interface ...
  • 249
1 vote
3 answers
162 views

Weighting guidelines to choose between a method and a function

Quite often I find difficult to decide between implementing operations as functions or as methods because I am not sure how to weight various well-known guidelines for this problem. I would like to ...
  • 119
-2 votes
2 answers
286 views

What are the disadvantages to using this form of pure DI in Python?

I want to perform dependency injection in my Python application without using reflection. My position on reflection is informed largely by the "don't hide things" philosophy (I am unable to ...
  • 105
3 votes
2 answers
2k views

What's the best way to get GitLab Docker runners and Python tox to work together?

I'm trying to get a better understanding of how tox and GitLab CI (with docker runners) would work together, as they seem to have a bit of overlap in what each does. I think I may be missing something ...
-1 votes
1 answer
232 views

How to organize top level scripts in Python projects, especially for interactively developing

I have a Python project that looks something like this. project/ tests/ __init__.py tests.py main_module/ __init__.py sub_modules/ ... task1.py ...
  • 107
-3 votes
1 answer
58 views

Should I design a class to handle my other class or the attribute of my other class?

Please allow me to illustrate my question with a simple example. Let's suppose we have a Customer class: class Customer: def __init__(self, name, surname, email): self.name = name ...
-1 votes
2 answers
263 views

Code repeated in multiple exception blocks

I'm starting to notice this pattern throughout some of my code: try: some_func() except FirstException as err: # known possible err # log err notify_user(err) except SecondException as ...
  • 1,037
0 votes
0 answers
57 views

What algorithm should I use to optimize a bike sharing redistribution system?

I want to optimize a bike-sharing redistribution system( find the best way for an agent to take bikes from a station that has more bikes than needed and relocate them to a station that needs more ...
-2 votes
2 answers
1k views

Is using nested try-except blocks problematic?

I've been seeing a lot of this construct throughout my application: def doSomething(): try: # setup some variables try: # do something that could throw an OSError ...
  • 1,037
3 votes
2 answers
9k views

Best practice for Python main function definition and program start/exit

What is best practice to define a main function and entry point for a script/module that may be used started as main, but not always? Here's how I've been doing it in the past, similar to realpython: ...
  • 141
26 votes
6 answers
8k views

What does it mean when you say C++ offers more control compared to languages like Python?

I am comparing C++ with Python. It is clear that C++ is much more efficient and that the C++ code compiles directly to machine code whereas in Python it is interpreted. I do understand that Python is ...
1 vote
1 answer
95 views

Should exception-blocks handle only exceptions raised from try-blocks?

Should the exception blocks in a try-except sequence be specific only to those exceptions which may originate from the try? Or can they be inclusive of exceptions that may arise from handling the ...
  • 1,037

1
3 4
5
6 7
39