0

Consider the following code:

class Test:
    def __init__(self):
        self._stuff = []

    def addStuff(self, what):
        self._stuff.append(what)
        stuff.append(what)

def addStuff(what):
    stuff.append(what)

stuff = ['item1', 'item2', 'item3']
addStuff('stuff1')
Test().addStuff('stuff2')
print stuff # ['item1', 'item2', 'item3', 'stuff1', 'stuff2']

This works perfectly fine and has the intended result. But, coming from Java, I feel compelled to do this:

class Test:
    def __init__(self):
        self._stuff = []

    def addStuff(self, stuff, what):
        self._stuff.append(what)
        stuff.append(what)

def addStuff(stuff, what):
    stuff.append(what)

stuff = ['item1', 'item2', 'item3']
addStuff(stuff, 'stuff1')
Test().addStuff(stuff, 'stuff2')
print stuff # ['item1', 'item2', 'item3', 'stuff1', 'stuff2']

The result is the same. Is there any real differences/benefits between the two? Which one is considered better practice/more Pythonic?

Hank
  • 125
  • 1
  • 11
  • 1
    It is always best practice to pass arguments and return values. Relying on global mutable state is bad – juanpa.arrivillaga Jan 12 '19 at 00:26
  • 1
    And this is true for most languages, it's not a Python-specific practice. – Barmar Jan 12 '19 at 00:52
  • 2
    The example is too artificial to determine a "right" option. None of this code makes any sense either way. With just a class named `Test` and a list named `stuff`, we can't tell how `Test` should know about `stuff`. All we can do is give the default advice of "mutable global state is usually bad". – user2357112 Jan 12 '19 at 00:59

1 Answers1

0

The second way is better. Using arguments is much more flexible because it allows different values to be used each time you call the function. If you ever wished to use another value in place of stuff within addStuff, you would have to make an entirely new function. Additionally, it's usually bad practice to use global variables because it can cause hard-to-find bugs and unnecessary complications.

See also: Why are global variables evil?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42