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
Well I just read a SOF thread where I see many people are talking about Python's ternary operator. I didn't know that Python has a ternary operator (ternary operator or conditional expression whatever you feel comfort with) equivalent though. So the syntax of Python ternary operator is...
play_golf if sun_shines else stay_dumb
Here Python will test the block sun_shines after if. If the block returns true it will execute the block play_golf before if otherwise Python will execute the block stay_dumb after else.
On the other hand I guess C's ternary operator is more readable.
sun_shines ? play_golf : stay_dumb
It is like asking a question sun_shines? True? Ok then play_golf otherwise stay_dumb.
Now my questions are...
How Python is Pythonic here? "Simple is better than complex" failed here in my opinion. If I am wrong please clarify me. I want to know what I am missing?
Execution order of C and Python conditional expression is completely different I see. So How it is equivalent of C? In the terms of folding multiple statements into one single expression?
Edit: I guess I got the answer to my 2nd question...
Python: true if true else false
C: true ? true : false
Now my questions are...
How Python is more Pythonic here? "Simple is better than complex" failed here in my opinion. If I am wrong please clarify me. I want to
know what I am missing?
The English sentence is
we go to the beach if the weather is nice, else we stay at home.
Highlight the right words, leave out the fillers:
gotobeach if weather == "nice" else stayathome
that looks a lot like valid Python ;)
Execution order of C and Python conditional expression is completely different I see.
No. It's not.
First, the line is parsed, then the condition after if is evaluated, then either one of the statements is evaluated.
Excerpt from the PEP 308 which defines the conditional expression:
Many C-derived languages use this syntax:
<condition> ? <expression1> : <expression2>
Eric Raymond even implemented this. The BDFL rejected this for
several reasons: the colon already has many uses in Python (even
though it would actually not be ambiguous, because the question
mark requires a matching colon); for people not used to C-derived
language, it is hard to understand.
In the PEP you can find the motivations of the decision, I find those appropriate, however this is just a personal opinion.
The parsing order is not different from C, as said by #Marcus Muller.
Related
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 1 year ago.
Improve this question
I was wondering if it was possible to make a keyword similar to 'and', or if it is part of the python compiler?
Thx
You can file a PEP (although good luck getting your new keyword accepted); or you can implement it yourself. Other than that, no: python doesn't allow dynamic syntax.
What you can do is look at the magic methods which are called by operators. Redefining these is sometimes handy. Pathlib makes it possible to do this:
from pathlib import Path
Path("a/b") / "c/d.txt"
And they didn't have to introduce any new operators or keywords, even though the usual meaning of / is division, not concatenation.
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
I'm starting to work and getting more familiar with Python in the context of data analytics and just got to know about list comprehensions which I find really elegant.
Although I'm aware there ist the risk of falling into love with it too much at the cost of readabilty, I really didn't find any guidelines or rules of thumb of when or when not to use it.
In my own code I used this generator expression inside a recursive function
--> find_children() is a user definded function to create hierarchical data
(find_children(ancestor) for ancestor in parents if len(parents) > 0)
instead of
if len(parents) > 0:
for ancestor in parents:
find_children(ancestor)
It looks more neat but that's actually the only reason for me.
So I would like to collect opinions of maybe some experienced Pythonistas and their approach regarding this or what best practice is.
List comprehensions are idiomatic python code and as such perfectly fine. Their main competitor is a functional style using map(), filter() etc. Both style are perfectly fine. I would probably refrain from using list comprehensions when you have long statements, e.g.
x["data"]["data"]["data"] for x in something] asks for trouble.
Also nested list comprehensions are evil, I personally see them as a code smell due to their poor readability.
Finally, the goal of good code is to be readable - when you finished a piece of code, step back and try to judge who readable your code really is. Introduce functions and variables to increase readability. List comprehensions are just a part of that picture.
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
First, why there is no end in python? Second, the fact that there is tabs and there is no end make python the best readable/beautiful language, why they do not introduce these characteristics in other languages?
You'll have to ask Guido van Rossum about why he didn't introduce an end construct, since it's a language design issue - but as you say, there are aesthetic reasons not to do so.
The reason this isn't introduced to existing languages is that there are already billions of lines of code written in them, and you don't want to force people to change all of that just for some aesthetics.
Why not have it as a backward-compatible change, such as e.g. allowing languages with C-like syntax to have the opening { but not the closing }? Probably because programmers in those languages are very used to it and might actually prefer it to not having closing marks, and probably don't see this as a useful feature. Also, it would be necessary to make it a per-file decision, as a mixture of explicit and implicit block ends would be extremely confusing and probably not parseable.
As a matter of fact, Python itself contains a joke about this, which I believe reflects the authors' opinion on the matter:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
(__future__ is a module which you can use to import certain pieces of functionality that were introduced in newer versions of Python and have been backported to older versions.)
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 8 years ago.
Improve this question
A quick function question in Python. Is it possible to stop a function from processing and return early. i.e like this:
def _do_something():
if not exists('/etc/', use_sudo=True):
# no files don't do any more
return
# if ok continue with stuff
sudo('/etc/init.d/nginx stop')
Is this ok? Or is there something like 'exit' ?
Your question sounds like " is there a better way to do this?".
no, that looks fine and will work.
For loops you could use the break-statement, but in a function this is good way to "stop" it - returning None implicitly.
Yes, this is a common way of structuring program logic.
Some people would argue that you write your function the other way around, like:
def _do_something():
if exists('/etc/', use_sudo=True):
sudo('/etc/init.d/nginx stop')
because it is shorter and, in a way, more directly represents what you mean by writing the function.
One thing to worry about with the structure that you have in your question is what happens when the function becomes more complicated. It is possible for a large and complicated function with many return statements to actually have unreachable code, where the function is guaranteed to return early and there is code at the end of the function that will not be executed.
def lol():
print "first!"
return
print "unreachable"
In this case, it is trivial to see that "unreachable" will never be printed, but if you have many nested if/else statements, this becomes less obvious. Good IDEs will warn you about unreachable code, but this is something to consider if you choose to program in a simpler text editor.
Side note: Just in case you weren't aware, Python functions that start with one or two underscores often have a "special meaning" attached to them. I'll leave the rest for you to explore.
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
Which is preferred
def method(self):
or
def method( self ):
With spaces in the parenthesis.
Check out PEP 8. It says to do the first one.
The common reference for Python style is PEP8, see: http://www.python.org/dev/peps/pep-0008/
To answer your question specifically, this is under "Pet Peeves":
Avoid extraneous whitespace in the following situations:
Immediately inside parentheses, brackets or braces.
Yes: spam(ham[1], {eggs: 2})
No: spam( ham[ 1 ], { eggs: 2 } )
There's PEP 8 the Python Style Guide:
http://www.python.org/dev/peps/pep-0008/
It suggests the former style, but note the introduction carefully.
I find the latter to be visual nails-on-chalkboard, personally.
http://www.python.org/dev/peps/pep-0008/
Python Style Guide
No space around the inside of function signatures. Occasionally I put space inside the parens of a function call if the arguments are particularly hairy, but never on the definition. I don't think any language makes a habit of that, actually.
I don't think you should blindly follow the PEP-8 style, like a vow upon a bible.
The PEP8 is intended for code that goes in the python standard library, i.e. the modules you can import just after you've installed Python, but they have very different development constraints than most of the software I write.
So I tend to think a lot about each "rule" (either from the PEP8, the pylint/pychecker ones, or the Google Style Guide) and see how it can apply to my code -- the pros and cons.
As for your question, people usually don't use spaces inside parentheses, although I've seen it in some code by coworkers that like it, IMHO it detracts a little from readability, but it's a minor issue.