简体   繁体   中英

Auto-PEP8 is adding lines by turning my lambda into def function, how do I disable this specific auto format?

I am using Visual Studio Code and PEP8 is automatically formatting a part of my code, I was just learning about lambdas and I had a 3 line code like this:

It went from this 3 line code:

# Lambda example
divide = lambda x, y: x/y
print(divide(10, 2))

To this 7 line code:

# Lambda example


def divide(x, y): return x/y


print(divide(10, 2))

Does anyone know how do I make this program to specifically not convert my lambda function into def function?

It has been formatting my code really good, so I don't want to completely disable this automatic feature, just for the lambda thing.

This is triggered by the pycodestyle code E731

You can disable this with --ignore=E731

In a config file (for instance tox.ini / setup.cfg):

[pep8] 
ignore=E731

There are some methods to disable auto converting lambda to function definition.

  • Using --ignore=E731 as explained by Anthony Sottile in (his/her) answer. Press Ctrl+, , search for autopep8 , and add item --ignore=E731 as shown in the following screenshot.

    在此处输入图片说明

  • Or you uninstall autopep8 first by invoking pip uninstall autopep8 and then install yapf via pip install yapf .

  • I let others add other methods from this line.

Another solution is to put parentheses around the lambda assignment:

divide = (lambda x, y: x/y)

autopep8 will not replace the above snippet with a def .

In general I would advise against this, as it goes against the PEP8 recommendations.

Nevertheless there are use cases for this, eg if the variable is conditionally assigned to different functions, which can look quite confusing when expressed using def s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM