Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a long with statement in python

Tags:

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?

like image 725
José Luis Avatar asked Apr 18 '13 10:04

José Luis


2 Answers

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.

like image 65
jamylak Avatar answered Oct 05 '22 07:10

jamylak


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.

like image 33
Martijn Pieters Avatar answered Oct 05 '22 06:10

Martijn Pieters