Pep8 Python3.3 Contradiction - coding-style

Pep 8 has the following rules
Blank Lines
Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as
whitespace; Many tools treat these characters as page separators, so
you may use them to separate pages of related sections of your file.
Note, some editors and web-based code viewers may not recognize
control-L as a form feed and will show another glyph in its place.
However, you can't have a completely blank line inside a class defintion
Example from my head:
class bunny:
def spam(self):
pass
def eggs(self):
pass
#a second example
class bunny2:
def __init__(self):
self._eggs = None
def eggs(self):
doc = "Spam and Eggs"
def fget(self, value):
return self._eggs
def fset(self, value):
self._eggs = value
def fdel(self):
del self._eggs
return locals()
eggs = property(**eggs())
The line between spam and eggs needs to be a blank line, however, that will result in a parse error of unexpected indentation. Is there another character that should go in that space? My assumption is just leave the spaces/tabs on the "blank" line because it is more readable.
In the second example nested defs need to have their previous lines indention maintained for the parse to work correctly.
What is the correct PEP 8 way to handle this? Blank line, blank line with white space, no line?

If you're working in the REPL, you can't have entirely blank lines. But there is no reason for code entered in the REPL to strictly adhere to PEP 8, anyway. But inside a file, it is a good idea to follow PEP 8.

Related

Sphinx issues mysterious error in literal blocks

In Sphinx (the ReStructuredText publishing system), are there any obscure rules that limit what a literal block can contain?
Background: My document contains many literal blocks that follow a double-colon paragraph, like this:
Background:... follow a double-colon paragraph, like this::
$ sudo su
# echo ttyS0,115200 > /sys/module/kgdboc/parameters/kgdboc
This block (with a different preceding paragraph) is one of the ones that issues an error: "WARNING: Inconsistent literal block quoting." The message indicates that the error is in the "echo" line. In the HTML output the literal block contains only the "sudo" line; the "echo" line is treated as ordinary text.
I haven't been able to identify any common property in the lines that report errors, or anything that distinguishes them, as a class, from lines in other literal blocks that don't get errors.
I stripped down the project to isolate the problem, and I identified it that way.
I had a numbered list item that contained a double-colon literal block that was indented only as far as the list item's text, like this:
2. Set up the... directory::
$ A Linux command
$ Another Linux command
$ And ANOTHER Linux command
$ etc.
When I indented the literal block further, the problem went away.
I was misled by two things:
The message does not point to the first line in the literal block, but to some apparently random line within it. In the case above, it pointed to the fifth line (out of eight) in the block!
In most cases this form of indention, although incorrect, works just fine.
Isolating the problem is a brute-force method of solving it, but is often effective when deduction fails. I'll keep that in mind in the future.

Reading and writing back yaml files with multi-line strings

I have to read a yaml file, modify it and write back using pyYAML. Every thing works fine except when there is multi-line string values in single quotes e.g. if input yaml file looks like
FOO:
- Bar: '{"HELLO":
"WORLD"}'
then reading it as data=yaml.load(open("foo.yaml")) and writing it yaml.dump(data, fref, default_flow_style=False) generates something like
FOO:
- Bar: '{"HELLO": "WORLD"}'
i.e. without the extra line for Bar value. Strange thing is that if input file has something like
FOO:
- Bar: '{"HELLO":
"WORLD"}'
i.e. one extra new line for Bar value then writing it back generates the correct number of new lines. Any idea what I am doing wrong?
You are not doing anything wrong, but you probably should have read more of the YAML specification.
According to the (outdated) 1.1 spec that PyYAML implements, within
single quoted scalars:
In a multi-line single-quoted scalar, line breaks are subject to (flow) line folding, and any trailing white space is excluded from the content.
And line-folding:
Line folding allows long lines to be broken for readability, while retaining the original semantics of a single long line. When folding is done, any line break ending an empty line is preserved. In addition, any specific line breaks are also preserved, even when ending a non-empty line.
This means that your first two examples are the same, as the
line-break is read as if there is a space.
The third example is different, because it actually contains a newline after loading, because "any line break ending an empty line is preserved".
In order to understand why that dumps back as it was loaded, you have to know that PyYAML doesn't
maintain any information about the quoting (nor about the single newline in the first example), it
just loads that scalar into a Python string. During dumping PyYAML evaluates how that string
can best be written and the options it considers (unless you try to force things using the default_style argument to dump()): plain style, single quoted style, double quoted style.
PyYAML will use plain style (without quotes) when possible, but since
the string starts with {, this leads to confusion (collision) with
that character's use as the start of a flow style mapping. So quoting
is necessary. Since there are also double quotes in the string, and
there are no characters that need backslash escaping the "cleanest"
representation that PyYAML can choose is single quoted style, and in
that style it needs to represent a line-break by including an emtpy
line withing the single quoted scalar.
I would personally prefer using a block style literal scalar to represent your last example:
FOO:
- Bar: |
{"HELLO":
"WORLD"}
but if you load, then dump that using PyYAML its readability would be lost.
Although worded differently in the YAML 1.2 specification (released almost 10 years ago) the line-folding works the same, so this would "work" in a similar way with a more up-to-date YAML loader/dumper. My package ruamel.yaml, for loading/dumping YAML 1.2 will properly maintain the block style if you set the attribute preserve_quotes = True on the YAML() instance, but it will still get rid of the newline in your first example. This could be implemented (as is shown by ruamel.yaml preserving appropriate newline positions in folded style block scalars), but nobody ever asked for that, probably because if people want that kind of control over wrapping they use a block style to start with.

Search for a pattern and print everything in between that in ruby

I have a file, I want to go over that file and any time it matches this "LINE_MATCH_START" and this is the only text in that line (except comments or preceding whitespace), I want it to print everything following it till it matches "LINE_MATCH_END" (which also has to be the only text in that line, comments are allowed but this has to be first thing in the line except whitespace). I want it to go over the entire file and save it as many times it catches it.
Example,
printf ("this is some text")
// comment LINE_MATCH_START this should be ignored
some_other_code
LINE_MATCH_START // can have spaces before it and comments after it
oh
this
should be
saved
LINE_MATCH_END
some_other_piece_of_code
LINE_MATCH_START
AGAIN
lets save this part as well
LINE_MATCH_END
From the above snippet, there can be space before the "LINE_MATCH_START" and it can have comments on the same line but no other piece of code.
I want my code to save all this part
oh
this
should be
saved
AGAIN
lets save this part as well
How can I do this in ruby?
This looks like it gets your output and maybe helps with an idea, but I would work on something more robust.
f = File.new('output.txt', 'w')
visible = false
IO.foreach('file_name') do |line|
case line
when /\s*LINE_MATCH_START.*/ then visible = true
next
when /\s*LINE_MATCH_END.*/ then visible = false
end
f.write(line) if visible
end

comma at the end of a dictionary - swift

Example code:
let interestingNumbers = [
"Prime":[2,3,5,7,11,13],
"Fibonacci":[1,1,2,3,5,8],
"Square":[1,4,9,16,25]`,`
]
Question: after "Square:[1,4,9,16,25]", there is a comma(sample code from Apple Swift reference guide book), when I get rid of it, I didn't get any error messages from Xcode, is this just convention at all ? (I remember there is a nil after array or dictionary in objective-C
This is because a comma after the last element in a dictionary is optional.
Consider the simpler example:
let letters = ["A":1,
"B":2,
"C":3
]
A comma placed after the last element, "C":3, is acceptable, but optional.
I believe that there is no specific convention regarding the final comma - some may prefer it as it allows you to add items on following lines without modifying the above line to add the comma (makes source control review simpler). I often leave commas on the last element in an enum declaration for the same reason.
If you know you are likely to add more elements in the future, then having the comma would simplify the source diff in a code review (one added line instead of one removed line and two added lines). I would use the comma where you know you're going to add elements later, and omit in if the list of items is final.

Delete first two lines of file with ruby

My script reads in large text files and grabs the first page with a regex. I need to remove the first two lines of each first page or change the regex to match 1 line after the ==Page 1== string. I include the entire script here because I've been asked to in past questions and because I'm new to ruby and don't always know how integrate snippets as answers:
#!/usr/bin/env ruby -wKU
require 'fileutils'
source = File.open('list.txt')
source.readlines.each do |line|
line.strip!
if File.exists? line
file = File.open(line)
end
text = (File.read(line))
match = text.match(/==Page 1(.*)==Page 2==/m)
puts match
end
Now, when You have updated your question, I had to delete a big part of so good answer :-)
I guess the main point of your problem was that you wanted to use match[1] instead of match. The object returned by Regexp.match method (MatchData) can be treated like an array, which holds the whole matched string as the first element, and each subquery in the following elements. So, in your case the variable match (and match[0]) is the whole matched string (together with '==Page..==' marks), but you wanted just the first subexpression which is hidden in match[1].
Now about other, minor problems I sense in your code. Please, don't be offended in case you already know what I say, but maybe others will profit from the warnings.
The first part of your code (if File.exists? line) was checking whether the file exists, but your code just opened the file (without closing it!) and still was trying to open the file few lines later.
You may use this line instead:
next unless File.exists? line
The second thing is that the program should be prepared to handle the situation when the file has no page marks, so it does not match the pattern. (The variable match would then be nil)
The third suggestion is that a little more complicated pattern might be used. The current one (/==Page 1==(.*)==Page 2==/m) would return the page content with the End-Of-Line mark as the first character. If you use this pattern:
/==Page 1==\s*\n(.*)==Page 2==/m
then the subexpression will not contain the white spaces placed in the same line as the '==Page 1==` text. And if you use this pattern:
/==Page 1==\s*\n(.*\n)==Page 2==/m
then you will be sure that the '==Page 2==' mark starts from the beginning of the line.
And the fourth issue is that very often programmers (sometimes including me, of course) tend to forget about closing the file after they opened it. In your case you have opened the 'source' file, but in the code there was no source.close statement after the loop. The most secure way of handling files is by passing a block to the File.open method, so You might use the following form of the first lines of your program:
File.open('list.txt') do |source|
source.readlines.each do |line|
...but in this case it would be cleaner to write just:
File.readlines('list.txt').each do |line|
Taking it all together, the code might look like this (I changed the variable line to fname for better code readability):
#!/usr/bin/env ruby -wKU
require 'fileutils'
File.readlines('list.txt').each do |fname|
fname.strip!
next unless File.exists? fname
text = File.read(fname)
if match = text.match(/==Page 1==\s*\n(.*\n)==Page 2==/m)
# The whole 'page' (String):
puts match[1].inspect
# The 'page' without the first two lines:
# (in case you really wanted to delete lines):
puts match[1].split("\n")[2..-1].inspect
else
# What to do if the file does not match the pattern?
raise "The file #{fname} does NOT include the page separators."
end
end

Resources