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 5 years ago.
Improve this question
Is there a recommended style when it comes to the use local variables inside a function? Should we use more explicit local variables as in style 1 or not as in style 2?
Two possible styles:
Style 1:
import re
def doc_to_lower(url_raw):
url_lower = [word.lower() for word in url_raw]
return url_lower
def process_data(url_raw):
url_split = re.split('//|/|-', url_raw)
url_lower = doc_to_lower(url_split)
return url_lower
url = 'http://www.bbc.com/sport/football/41653935'
tokens = process_data(url)
for token in tokens:
print(token)
Style 2:
import re
def doc_to_lower(url_raw):
return [word.lower() for word in url_raw]
def process_data(url_raw):
return doc_to_lower(re.split('//|/|-', url_raw))
url = 'http://www.bbc.com/sport/football/41653935'
tokens = process_data(url)
for token in tokens:
print(token)
Pretty sure this is a case where personal opinions will arise. But for me, situation 2 represent a more pythonic way of representing things.
The main reason of my answer is the fact that your function name in this case says it all. I declare local variable only if I have to or if it helps for readability.
Hope it helps
EDIT
To demonstrate my answer take this part of your code,
Style 1:
def process_data(url_raw):
url_split = re.split('//|/|-', url_raw)
url_lower = doc_to_lower(url_split)
return url_lower
Style 2:
def process_data(url_raw):
return doc_to_lower(re.split('//|/|-', url_raw))
If I were to reuse your code, at a glance I'd think style 1 return a lowered url and would understand that in style 2 the function is used to processed data.
I'm not trying to say that I'm an expert or anything and this is debatable, I'm just trying to clarify my point.
I prefef style 2, because I find it easier to read.
I can think of two reasons to use style 1 in certain cases:
When the expression becomes very complex. Using style 1 you can split up parts of the expression and assign it a readable name.
When the value of a subexpression must be available for an assert statement, debugging or a test case.
Great question and well done for thinking about readability all the time, making it easier down the line.
I think my answer would have to be follow the coding standard of your place of work where possible. This is most important, there should be consistency with the other developers you are working with.
If there is no coding standard, arrange a meeting and write one up together. That way you're all workingfrom the same script (pardon the pun) and the code will be readable to everyone.
My personal preference would be the explicit version. For me it would be clearer what was going on and thus reduce my own errors. However I understand that some would see this as a slight overkill in simple examples. I guess it comes down to what languages you learnt first and how and where you learnt them.
Related
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
for pl in pokemon_list:
if pl["pokemon"] == showtype:
result = f"stamina: {'{:.2f}'.format((pl['stamina']/statmax)*100)}% ("
for i in range(pl["stamina"]):
result += "*"
How do I convert the code above to a more pythonic way?
First, using str.format() inside of an f-string is not sensible. Pick one
technique or the other, depending on the situation. For readability and
maintainability, do the computations outside of the f-string. An f-string is an
awkward context for computation; but it's perfect for simple variable
interpolation. In your case, you'd probably be better off sticking to
format().
Second, list comprehension is just a tool. It's not the holy grail of Python.
Select the tool only when it makes sense. One key test is whether you want
to create a list. You do not, as far as I can tell.
Your comment implies that you want to return the first matching item during the
iteration. If so, just do it. While you're at it, help your reader by using
convenience variables to reduce the visual weight of the code.
fmt = "stamina: '{:.2f}'% ({}"
for pl in pokemon_list:
if pl["pokemon"] == showtype:
s = pl['stamina']
return fmt.format(100 * s / statmax, '*' * s)
Could this be rewritten in the style of a comprehension? Yes, but it would be
less readable, even after breaking it apart into three lines of code. Avoid the
temptation to write overly fancy code like this, which will just leave your
readers scratching their heads.
fmt = "stamina: '{:.2f}'% ({}"
gen = (
fmt.format(100 * pl['stamina'] / statmax, '*' * pl["stamina"])
for pl in pokemon_list:
if pl["pokemon"] == showtype
)
return next(gen, None)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I write following while loop in python?
int v,t;
while (scanf("%d %d",&v,&t)==2)
{
//body
}
Python being a higher level language than C will normally use different patterns for this kind of situation. There is a deleted question that in fact had the exact same behavior than your C snippet - and thus would be "correct", but it became so ugly a piece of code in Python it was downvoted pretty fast.
So, first things first - it is 2015, and people can't simply look at a C's "scanf" on the prompt and divine they should type two white space separated integer numbers - you'd better give then a message. Anther big difference is that in Python variable assignments are considered statements, and can't be done inside an expression (the while expression in this case). So you have to have a while expression that is always true, and decide whether to break later.
Thus you can go with a pattern like this.
while True:
values = input("Type your values separated by space, any other thing to exit:").split()
try:
v = int(values[0])
t = int(values[1])
except IndexError, ValueError:
break
<body>
This replaces the behavior of your code:
import re
while True:
m = re.match("(\d) (\d)", input()):
if m is None: #The input did not match
break #replace it with an error message and continue to let the user try again
u, v = [int(e) for e in m.groups()]
pass #body
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I liked the idea of Literate CoffeeScript and wanted to see if I could get something working with Python. I tried to accomplish something similar to this simple Literate Ruby and ended up with the following. The program takes Literate Python in standard input, a file, or list of files and executes just the code.
import fileinput
import re
code = ''
for line in fileinput.input():
match = re.match(r'([ ]{4}|\t)(.*)', line)
if match:
code += match.group(2) + '\n'
exec code
A simple Literate Python file.
# Python Hello World Program
A simple example of a Literate Python Hello Word program.
print "hello world"
I'm new to Python and wanted to know if I'm missing something or if there is a better solution.
As I said in a comment, eval or exec are evil, a better alternative is to use the code module as in the following example. Also, you may prefer to compile the regex, in order to only perform the matching at each iteration over the input instead of building the automaton at each iteration.
import fileinput
import code
console = code.InteractiveConsole(locals())
import re
r = re.compile(r'([ ]{4}|\t)(.*)')
code = ''
for line in fileinput.input():
match = r.match(line)
if match:
console.push(match.group(2))
Though that example will output the results on sys.stdout so you may want to use instead an overloaded class such as the one in this example.
Combing python and markdown-like syntax is best done using tools rather than changing the language. For example:
sphinx (render output from restructured text in doc strings or other files, both of which may have embedded code samples)
ipython notebook (a combination of "cells" with either markdown or python code)
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 2 years ago.
Improve this question
I'm writing a program that will create a binary tree of the Morse Code alphabet (as well as a period and an apostrophe), and which will then read a line of Morse Code and translate it into English. (Yes, I know that a look-up table would be easier, but I need to sort out my binary trees). I think a good bit of my problem is that I want to put the values into the tree in alphabetical order, rather than by symbol order. But surely there must be a way to do that? Because if I had a million such values that weren't numeric, I wouldn't need to sort them into the simplest order for insertion...right?
It's reading from a text file where each line has one sentence in Morse Code.
- .... .. ... .. ... ..-. ..- -. .-.-.- for example, which is "This is fun."
1 space between symbols means it's a new letter, 2 spaces means it's a new word.
As it stands, I'm getting the output ".$$$" for that line given above, which means it's reading a period and then getting an error which is symbolized by ('$$$'), which is obviously wrong...
Like I said before, I know I'm being complicated, but surely there's a way to do this without sorting the values in my tree first, and I'd like to figure this out now, rather than when I'm in a time crunch.
Does anyone have any insight? Is this something so horribly obvious that I should be embarrassed for asking about it?
Welcome to SO and thanks for an interesting question. Yes, it looks to me like you're overcomplicating things a bit. For example, there's absolutely no need to use classes here. You can reuse existing python data structures to represent a tree:
def add(node, value, code):
if code:
add(node.setdefault(code[0], {}), value, code[1:])
else:
node['value'] = value
tree = {}
for value, code in alphabet:
add(tree, value, code)
import pprint; pprint.pprint(tree)
This gives you a nested dict with keys ., -, and value which will be easier to work with.
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 2 years ago.
Improve this question
Is it considered bad style to assign values to variables like this?
x = "foobar" or None
y = some_variable or None
In the above example, x gets the value 'foobar'.
No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.
The primary danger of doing something like this is the possibility that (in the second case) some_variable is False but not None (the integer 0, for instance) and you don't want to end up with y equal to None in that case.
I also feel a bit unconfortable using that kind of expressions. In Learning Python 4ed it is called a "somewhat unusual behavior".
Later Mark Lutz says:
...it turns out to be a fairly common coding paradigm in Python: to
select a nonempty object from among a fixed-size set, simply string
them together in an or expression. In simpler form, this is also
commonly used to designate a default...
In fact, they produce concise one-line expressions that help to eliminate line noise from the code.
This behavior is the basis for a form of the if/else ternary operator:
A = Y if X else Z
OP's syntax is perfectly fine.
The official name for "assignment with or" is null coalescing and there's actually a Wikipedia page about it now! https://en.wikipedia.org/wiki/Null_coalescing_operator
This question may be useful as well:
Is there a Python equivalent of the C# null-coalescing operator?