Is there a Python convention to avoid long lines of code? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Should I create variables just to avoid having long lines of code? For example, in the code below the variable stream_records is only used once after it's set.
stream_records = stream.get_latest_records( num_records_to_correlate ).values('value')
stream_values = [float(record['value']) for record in stream_records]
Should I have done this instead?
stream_values = [float(record['value']) for record in stream.get_latest_records( num_records_to_correlate ).values('value')]
I am trying to optimize for readability. I'd love some opinions on whether it's harder to have to remember lots of variable names or harder to read long lines of code.
EDIT:
Another interesting option to consider for readability (thanks to John Smith Optional):
stream_values = [
float(record['value'])
for record in stream.get_latest_records(
num_records_to_correlate
).values('value')
]

PEP 8 is the style guideline from the beginning of Python, and it recommends that no source lines be longer than 79 characters.
Using a variable for intermediate results also performs a kind of documentation, if you do your variable naming well.

Newlines (carriage return) inside parentheses count as blank.
The same applies to newlines inside brackets, as pointed out by Bas Swinckels.
So you could do something like that:
stream_values = [
float(record['value'])
for record in stream.get_latest_records(
num_records_to_correlate
).values('value')
]
You can also use \ to continue a statement on the following line.
For example:
long_variable_name = object1.attribute1.method1(arg1, arg2, arg3) + \
object2.attribute2.method2(arg1, arg2, arg3)

the first one is definitely easier to read so if there are no performance concerns I would totally go for more variables as long as they have self-explanatory names. it's also way easier to debug if somebody (not you) has to.

The first one is indeed more readable. Creating a variable doesn't cost you a lot here, so you can leave your code with it. Plus, if you are debugging it, it will be much easier to see if the error comes from the call of get_latests_records or from your list comprehension.
However, another way nice way would be to construct your list with the map function:
stream_values = map(lambda x: float(x['value']),
stream.get_latest_records(num_records_to_correlate) \
.values('value')])
The lambda here is necessary, to apply float on the correct value of the dictionary. As you can see, I have limited the number of chars per line to respect the PEP8 convention, which can help to make the code readable too.

Related

How do I check if a string contains ANY element in an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to detect if a string contains any element in an array. I want to know if the string(msg) has any element from the array(prefixes) in it.
I want this because I want to make a discord bot with multiple prefixes, heres my garbage if statement.
if msg.startswith(prefixes[any]):
The existing answers show two ways of doing a linear search, and this is probably your best choice.
If you need something more scalable (ie, you have a lot of potential prefixes, they're very long, and/or you need to scan very frequently) then you could write a prefix tree. That's the canonical search structure for this problem, but it's obviously a lot more work and you still need to profile to see if it's really worthwhile for your data.
Try something like this:
prefixes = ('a','b','i')
if msg.startswith(prefixes):
The prefixes must be tuple because startswith function does not supports lists as a parameter.
There are algorithms for such a search, however, a functional implementation in Python may look like this:
prefixes = ['foo', 'bar']
string = 'foobar'
result = any(map(lambda x: string.startswith(x), prefixes))
If you search for x at any position in string, then change string.startswith(x) to x in string.
UPDATE
According to #MisterMiyagi in comments, the following is a more readable (possibly more efficient) statement:
result = any(string.startswith(prefix) for prefix in prefixes)

Regex for getting everything in between brackets, including parentheses [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a string I am trying to create a regex for in order to extract everything inside the brackets. An example of such a string is as follows
[-At(A),+CarAt(B),-CarAt(A),-InCar]
The current regex I'm using is re.search(r'\[.*?\]', string), but this only returns -At(A),-InCar instead of -At(A),+CarAt(B),-CarAt(A),-InCar
I am not sure why it's matching one set of parentheses in -At(A); I thought the regex I had would work because it would match everything between the brackets.
How can I get everything inside the brackets of my original string?
I think the problem is with the question mark. Because question marks, when they come after a quantifiers make them 'lazy'.
So try to use:
r'\[.*\]'
You didn't say you wanted the contained members, but I suspect it to be the eventual case
To do so, I've found it better to slice or .strip() brackets off and then .split() this sort of string to get its members before doing further validation
>>> s = "[-At(A),+CarAt(B),-CarAt(A),-InCar]"
>>> s = s.strip('[]')
>>> s
'-At(A),+CarAt(B),-CarAt(A),-InCar'
>>> values = s.split(',')
>>> values
['-At(A)', '+CarAt(B)', '-CarAt(A)', '-InCar']
Using a regex to validate the individual results of this is often
easier to write and explain
is better at highlighting mismatches than re.findall(), which will silently omit mismatches
can be much more computationally efficient (though it may not be for your case) than trying to do the operation in a single step (ex1 ex2)
>>> import re
>>> RE_wanted = re.compile(r"[+-](At|Car|In){1,2}(\([A-Z]\))?")
>>> all((RE_wanted.match(a) for a in values))
True

Shorten the regex usage syntax in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I apologize because I am coming from Perl and I am new to Python.
The following example looks very long to me:
#!/usr/bin/python
import re
r = re.compile('(?i)m(|[ldf])(\d+)')
m = r.match(text)
if m:
print m.group(2)
In Perl for example it is only one line and it's pretty readable.
#!/usr/bin/perl
print $2 if /m(|[ldf])(\d+)/i
How can I rewrite my Python example to be simpler. If possible to be as light as it is with Perl.
I am planning to write plenty tests and if I want to keep my code readable I would like to avoid consuming lines that will not help people to understand my program. I guess that something like this below would be more readable that my first solution:
r = R()
if r.exec('(?i)m(|[ldf])(\d+)', text): print r.group(2)
if r.exec('(?i)k(|[rhe])(\d{2})', text): print r.group(2)
Unfortunately in this case I have to write a class for this.
The Python way values clarity over brevity, so things are generally going to be more verbose than they are in Perl. That said, the re.compile step is optional.
m = re.match('(?i)m(|[ldf])(\d+)', text)
if m:
print m.group(2)
In Python, assignments are not expressions; they can't be used as values. So there's no way to skip the separate assignment statement (m = ...) or combine it with the if . And if you want to refer to the match object later, you do need an explicit assignment - there's no global implicit state analogous to the Perl $n variables that stores the capture groups automatically.

(Python) Coding style parentheses in ifs, loops, etc [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Just your personal preference, which do you prefer?
if filename in filesAndFoldersList:
while a != "TEST":
a = input("Input: ")
Or
if(filename in filesAndFoldersList):
while(a != "TEST"):
a = input("Input: ")
Either one works, so this is just personal preference I think. Second one is more similar to Java/C++. But which you do prefer and why?
You should never use parentheses directly after the keyword of a statement, as you do in your second style. You are confusing the reader by making it look like they are functions. All you are doing is group the expression in parentheses, Python will ignore these and all you have achieved is the removal of the space after the keyword.
Neither can you use the style with all compound statements; you cannot use the style with a for loop or a with statement that includes the as <target> clause.
The Python Style Guide makes no mention of the second (parenthesized) style, at all; it makes the assumption that no-one would use it.
Note that this is separate from using parentheses around long expressions, where you use (...) around the if condition expression if it is otherwise too long to fit on a single line. In such a situation you want to put a space between the opening ( and the if keyword:
if (
this_is_one_thing and
that_is_another_thing or
(more_conditions and such_things)
):
do_something()

How to name a list variable with ending "s" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
How should one name a list variable with ending s:
fpss,frame_rates, audios,
or
fps_records = []
frame_rate_records = []
audio_records = []
I don't think adding _records to the end adds anything of value. Avoid adding length to names that don't add clarity or insight for future reviewers, which will certainly include yourself. Adding meaningless verbiage will only serve to make your code harder to read and therefore harder to maintain.
If you think you're going to look at fps later and forget it's a list, use fps_list, which directly tells what type it is to any reader.
Please no-one interpret me as suggesting Hungarian notation. But I do do this when I'm starting out with a list, realize order doesn't matter and I need set-like behavior, and then realize I actually needed a mapping in the first place. Using that sort of convention allows me to implement my new structure completely without breaking the old.
For example, see this Python-style pseudo-code:
Iteration 1
def foo():
data = []
get_data_from_source()...
Iteration 2
def foo():
data_list = []
data_set = set()
get_data_from_source()...
Iteration 3
def foo():
data_set = set()
data_dict = {}
get_data_from_source()...
Iteration 4
def foo():
data = {}
get_data_from_source()...
return data
I agree with #Arone, however if required I would go with adding lst(like lst_records) with list(same we follow in legacy lang like vb) variables so if you would start typing lst immediately IDE would start suggesting all list.

Categories