开发者

Python: catching mutable default arguments

开发者 https://www.devze.com 2023-01-25 10:04 出处:网络
I know about the problem and how to fix it. I would like to ask for help finding this problem in existing code.

I know about the problem and how to fix it. I would like to ask for help finding this problem in existing code.

In other words, I'm trying to find all loc开发者_如何学Pythonations where this trap is buried, so I can fix it.

Is there any tool that can help me?


Pylint has a warning for default argument values of mutable types. It's customizable, so you could get it to just do this if you wanted.


What's wrong with grep?

grep "^\s*def.*=(\[\]|\{\}|set\(\))"

This will find just about all of the usual culprits.

If you're using a instance of one of your own mutable classes as a default value, you'll have to check for that separately.


The regex proposed by @S.Lott is also finding function/method calls, but we just want to find function/method definitions.

So here is an updated version of the regex to find the location of all function/method signatures which uses mutable default argument:

def .+?\([^:]*?(=\[\]|=\{\}|set\(\))[^:]*?\):

Note:

if you are using PyCharm, it will add a yellowish background to these arguments and help you change the code.

Enjoy!

0

精彩评论

暂无评论...
验证码 换一张
取 消