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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With