[Tutor] Long Lines techniques
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Dec 13 20:03:55 EST 2018
On 13/12/2018 17:36, Avi Gross wrote:
> When lines get long, what points does splitting them make sense and what
> methods are preferred?
Its down to personal preference and convenience
plus a smidge of idiom.
> Yes, I am aware of ways to break up something long by breaking in into
> multiple statements. It feels silly to do this:
>
> A = "long string"
> B = "another string"
> .
> Z = "last string"
I'd probably suggest
stgs = ''.join([
"long string",
"another string",
...
"last string"
])
> There are places you can break lines as in a comprehension such as this set
> comprehension:
> letter_set = { letter
> for word in (left_list + right_list)
> for letter in word }
You can break anythiong anywhere (pretty much) inside a set of
parens/brackets/braces.
> So clearly when you use [.] it ignores indentation until it gets to the end.
Indentation only matters for blocks, inside parens etc it
doesn't signify.
> But python has a few features like allowing a comma at the end of a tuple
> that get in the way:
>
>>>> x,y = 1,
There's no parens to hold the subsequent line.
You have expressed a valid single value tuple.
> One that seems not to be favored is a backslash at the end of a line:
>>>> x = 1 + \
> 2 + \
> 3
Its easy to get wrong and rarely needed but if its the
only way to get neat code its acceptable.
> I will stop here with saying that unlike many languages, parentheses must be
> used with care in python as they may create a tuple
Not a tuple, they arecreated with commas.
But parens are used to disambiguate tuples
- for example in argument lists. But its the comma that makes it a tiuple:
t = 5,6 # 5,6 is a tuple
a,b = t # a->5, b->6
> or even generator expression.
These are usually just parens in a function. The generator
expression is the bit inside (not including) the parens.
> Curly braces may make a set or dictionary. Options for splitting
> the code without messing up indenting cues would be nice to understand.
Braces and square brackets do create structures,
but you can break lines within those. Indeed its very
common to define large literal structures across
multiple lines (possibly including descriptive comments):
mydict = {
"key" : 42, # the first key
"two" : 66 # another key
...
}
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list