简体   繁体   中英

How to break a long with statement in python

I have a line of code in python like this:

with long_name_function(p) as a, other_long_name_function():

and I want to break it in multiple lines, because is too long, I could use backslashes, but they are considered a bad practice. I also could use contextlib.nested, but is deprecated, is there any other alternative?

This disregards the premise of the question but I would actually recommend using backslashes in this case:

with really_really_long_name_function(p) as f1, \
        other_really_really_long_name_function() as f2:
    pass

As @JonClements said, you can't use brackets or commas in this case, there's no alternative so backslashes are the way to go and the code looks pretty clean IMO.

If you want to avoid backslashes, you can alias the long names:

lnf = long_name_function
olnf = other_long_name_function
with lnf(p) as a, olnf():
    # ...

or you could nest the statements:

with long_name_function(p) as a:
    with other_long_name_function():
        pass

You do not want to use contextlib.nested() ; there are several problems with it that directly led to its deprecation. Earlier context managers are not covered for problems with later context managers in the nesting, for example.

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