[python-users] Fwd: Nachschlag zu gestern

Alexander Lazarević laza at e11bits.com
Do Feb 13 10:30:35 CET 2020


Moin,
also das Tutorial warnt wirklich ausdrücklich:
*Important warning:* The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary,
or instances of most classes. For example, the following function
accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))print(f(2))print(f(3))

This will print

[1][1, 2][1, 2, 3]

flake8(3.7.9) hat da wohl kein Problem mit. Und vor zwei Jahren darauf
angesprochen sah man wohl keinen großen Bedarf das zu erkennen (
https://gitlab.com/pycqa/flake8/issues/386#note_45347918).
Benutzt man das flake8 plugin bugbear, dann bekommt man aber folgende
aussagekräftige Warnung:

doodoo.py:1:16: B006 Do not use mutable data structures for argument
defaults.  They are created during function definition time. All calls to
the function reuse this one instance of that data structure, persisting
changes between them.


pylint gibt einem aus dem Stand (u.a.) folgende Warnung aus:

doodoo.py:1:0: W0102: Dangerous default value [] as argument
(dangerous-default-value)
Zu Keyword-Only Arguments (https://www.python.org/dev/peps/pep-3102/)

def compare(a, b, *, key=None):

gibt es wohl ab python 3.8 auch die Entsprechung zy Positional-Only
Parameters (https://www.python.org/dev/peps/pep-0570/ oder besser erklärt
in https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters)

def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

The following is a valid call:

f(10, 20, 30, d=40, e=50, f=60)

However, these are invalid calls:

f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword
argumentf(10, 20, 30, 40, 50, f=60)           # e must be a keyword
argument

Viele Grüße,
 Alex
-------------- nächster Teil --------------
Ein Dateianhang mit HTML-Daten wurde abgetrennt...
URL: <http://lists.uni-koeln.de/pipermail/python-users/attachments/20200213/73753416/attachment.html>


Mehr Informationen über die Mailingliste python-users