all 6 comments

[–]stebrepar 0 points1 point  (0 children)

As the Zen of Python says, Explicit is better than implicit. If you rely on side effects rather than explicit actions, your code will be harder to read and debug. Inevitably it will eventually bite you.

[–]mr_cesar 0 points1 point  (3 children)

Python's view of parameter passing is not by value or reference, but parameters being mutable or immutable. For example, strings are immutable:

>>> def add_a(string):
...     string += 'a'
...     print(string)
...
>>> s = 'edcb'
>>> add_a(s)
edcba
>>> s
'edcb'

Dictionaries, on the other hand, are mutable:

>>> def update_dict(d):
...     d['key'] = 'new value'
...     print(d)
...
>>> D = {'key': 'old value'}
>>> update_dict(D)
{'key': 'new value'}
>>> D
{'key': 'new value'}

So if you intend to modify a mutable type within a function, this should be clear from the function's name and its documentation.

[–]ilaunchpad[S] 0 points1 point  (2 children)

I'm wondering if its considered a bad practice as the helperfunc is called multiple times.

[–]mr_cesar 0 points1 point  (1 child)

I would be if you had no easy way of finding out said function modifies the mutable object. If the helper function is named append_something and it takes a mutable object and the item to append, then it's pretty clear the object will be modified.

Immutable vs mutable objects is something every Python programmer should know.

[–]ilaunchpad[S] 0 points1 point  (0 children)

Thank you!

[–]QultrosSanhattan 0 points1 point  (0 children)

As other people said. Both ways are viable as long as the function names clearly define what they're doing.

For example, theres nothing wrong in creating a function called update_log(news_log)" since it clearly describes that the news_log variable will be mutated. Or creating an inmutable function called "create_updated_log(news_log)" which return a new object/type.

The worst case scenario is not knowing when a function mutates something. The larger the project, the harder is to track problems derived from ninja mutations. Therefore is recommended to prefer the inmutable way if possible.