Assignment with "or" in python [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 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?

Related

How to make the code to more pythonic way [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
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)

Why does variable locate before the loop [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 3 years ago.
Improve this question
Why is the position of a loop header relative to the body is different from its usual one? How come a loop variable appears before the loop?
The code is taken from various programs
n=reduce(operator.mul,[int(x) for x in str(n)],1)
return value == sum(int(x) ** len(str(value)) for x in str(value))
It is, technically, not a loop. This is so-called comprehension syntax, borrowed into Python from Haskell (see comments for the full lineage). To follow traditions of math notation for sets, and distinguish a comprehension from a usual loop, loop-like enumerator comes in the end of the notation.
Find more of history of various comprehensions and generator expression in Python here http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html
NOTE. The first of your expression contains a list comprehension, the list comprehension is the first and the most popular pythonic comprehension. The second one contains a generator expression, which, though, originally were called generator comprehension, according to PEP 289.

Best practice: local variables in a function (explicit vs implicit) [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 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.

Best practices for using brackets in python expressions? [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
In Python, I have come to the realisation that when writing an expression, you can use brackets if you want to. I'll give you an example:
while count > 10:
and
while (count > 10):
are both accepted by the compiler.
My question is what are the best practices when using brackets for expressions in python? i.e. when should you use brackets in expressions?
In the example you provide, brackets are not necessary. They clutter the code without any particular reason (that I can think of)
Some reasons to use brackets. Use brackets to:
1) Improve code clarity
a * b + c and (a * b) + c are equivalent, but the latter is clearer. The clarity aspect is even more evident when combining more complex code, like ternary operations.
2) Override default order of operations
(a + b) * c and a + b * c give different behavior.
Similarly, X or Y and Z is different from (X or Y) and Z.
Additionally, use of brackets can alleviate the need for the programmer to memorize the implicit order of evaluation by explicitly specifying the order.
I always write brackets because I'm used to from languages that actually require them (C, Java...). In my opinion it is also make the code easier to read.
However, brackets are only useful when actually needed, like computing compound expressions. There's no really other reason to add brackets.
Only when it creates clarity of purpose.
if (condition_one and condition_two) or condition_three:
is okay, even though if you remove the parens it still works identically. It's not immediately obvious that and has a higher operator precedence than or (unless you've taken the time to memorize it). Similarly no one faults you for doing that with the math:
(2 * 3) / 6
Obviously if you need to override operator precedence, brackets are the way to do it
(2 + 3) / 6 != 2 + 3 / 6
condition_one and (condition_two or condition_three) != \
condition_one and condition_two or condition_three
However parens do add extra "noise" to the line that isn't necessary. Use them sparingly and only when actually necessary.
if (this) and (that) and (the_other):
should be
if all([this, that, the_other])
or at least
if this and that and the_other

Math brackets in python? [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 9 years ago.
Improve this question
Now I'm talking about MATH brackets, not python brackets, I know that parentheses () work like in maths, ex:
i = 5*(2+2)
print (i)
#output = 20
But square brackets [] and curly brackets {} don't work... (I know why they don't work)
Thank you,
Using Python 3.2.2
You don't need "math" brackets -- just use nested parentheses. Humans use [] in writing out complex math expressions to make them more readable to other humans, but this isn't necessary. They don't mean anything different than regular parentheses. So, when writing code, just stick to the parentheses.
They don't work as grouping constructs - only parentheses will do that.
Square brackets define a list.
Curly brackets define either a set or a dictionary (if the elements appear as key: value).
Further to this, the extra level of clarity when dealing with multiple nestings is unnecessary, as most good IDEs will let you know when the parentheses count is imbalanced (and, you will also notice when the count is imbalanced from repetition).

Categories

Resources