Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding global variables but also too many function arguments (Python)

Let's say I have a python module that has a lot of functions that rely on each other, processing each others results. There's lots of cohesion.

That means I'll be passing back and forth a lot of arguments. Either that, or I'd be using global variables.

What are best practices to deal with such a situation if? Things that come to mind would be replacing those parameters with dictionaries. But I don't necessarily like how that changes the function signature to something less expressive. Or I can wrap everything into a class. But that feels like I'm cheating and using "pseudo"-global variables?

I'm asking specifically for how to deal with this in Python but I understand that many of those things would apply to other languages as well.

I don't have a specific code example right, it's just something that came to mind when I was thinking about this issue.

Examples could be: You have a function that calculates something. In the process, a lot of auxiliary stuff is calculated. Your processing routines need access to this auxiliary stuff, and you don't want to just re-compute it.

like image 528
Lagerbaer Avatar asked Oct 08 '15 18:10

Lagerbaer


People also ask

Should you avoid using global variables in Python?

The use of global variable in python is considered bad practice and should generally be avoided. Instead the user can try and use a parameter for passing a value onto a function or return a value to obtain it.

How many function arguments is too many Python?

Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.

Why are global variables not recommended?

Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code.

How do you avoid global variables?

The simplest way to avoid globals all together is to simply pass your variables using function arguments. As you can see, the $productData array from the controller (via HTTP request) goes through different layer: The controller receives the HTTP request. The parameters are passed to the model.


1 Answers

This is a very generic question so it is hard to be specific. What you seem to be describing is a bunch of inter-related functions that share data. That pattern is usually implemented as an Object.

Instead of a bunch of functions, create a class with a lot of methods. For the common data, use attributes. Set the attributes, then call the methods. The methods can refer to the attributes without them being explicitly passed as parameters.

like image 122
RobertB Avatar answered Sep 28 '22 09:09

RobertB