3

I have a general question about Python best practices. Tried googling for an answer, but didn't find anything relevant. The question is : is it best practice to explicitly pass a globally known parameter to a function?

So, is this best practice?

a = 1

def add_one(a):
 b = a + 1

or this?

a = 1

def add_one():
 b = a + 1


user2071786
  • 121
  • 1
  • 10
  • 1
    If the function should use the variable in some way, then making it a forced argument will make it easier to debug in the future. – Hampus Larsson Sep 13 '20 at 10:40
  • 4
    It's usually best practice to avoid global variables. The first does not even use the global `a` but shadows it. – Jan Sep 13 '20 at 10:41
  • 3
    Agreeing with @Jan - best not to use globals. (FWIW; I’ve never found a use for them). Rather, if you need a value to be accessed by several functions, consider making it a class attribute, (e.g. `self._a`). – S3DEV Sep 13 '20 at 10:52

1 Answers1

3

Here is an answer to expand on my comment regarding setting a as a class attribute, rather than using a global.

The Short Answer:

Class Example:

Here is a simple, stripped down class structure with no frills. You'll notice the absence of any global variables, along with no passed variables.

This is not saying that passed variables are discouraged, they are useful, if not necessary. However, this is to show that globals are not needed, and there's usually a better way. For what it's worth ... (personally speaking, I've never seen the use for them in Python).

class Demo():
    """Class attribute demonstration class."""
    
    def __init__(self):
        """Demo class initialiser."""
        self._a = 73
        
    def add_one(self):
        """Add one to the `a` attribute."""
        self._a += 1
        
    def times_two(self):
        """Multiply the `a` attribute by two."""
        self._a *= 2

Use Case:

I'll be the first to point out that this example is all but useless in the real world due to 1) externally accessing a 'private' class attribute and 2) the continued updating of _a; this is only an example specific to your question.

Note that each call to a different function has a different, yet continued affect on _a; noting the variable (class attribute) is neither global, nor passed.

demo = Demo()
print(f'Value of _a: {demo._a}')
>>> Value of _a: 73

demo.add_one()
print(f'Value of _a plus one: {demo._a}')
>>> Value of _a plus one: 74    

demo.times_two()
print(f'Value of _a plus one, times two: {demo._a}')
>>> Value of _a plus one, times two: 148
S3DEV
  • 8,768
  • 3
  • 31
  • 42