Python style question, function parameters [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 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.

Related

Should i annotate types everywhere? [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 3 years ago.
Improve this question
Should i annotate types in my unit tests functions?
What also with overridden django methods like save and get or post functions in generic view?
This is arguably an opinion question but I think that there is a generally accepted answer, which is roughly "No".
One way of categorising programming languages is into statically typed and dynamically typed. Statically typed languages are generally more robust, especially for "programming in the large", and dynamically typed languages have advantages ito programming speed, and in modelling problems where it is beneficial to be able to accept data of various types. Type hints try to strike a balance. The rough rule being: if you are using the dynamic nature of the language to achieve something, don't worry about annotating it. If however, you are writing code that doesn't make specific use of the dynamic nature of the language, annotate
Perhaps to make the point clear, consider that if you DO annotate everything, well then why not just use Cython? Same effort but you actually get some speed up as well. The reason people use Python with annotations instead of Cython is that some problems are naturally better solved without specifying types.

Python imports: using abbreviated import names [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 3 years ago.
Improve this question
I am trying to determine some best practices of function imports and PEP 8 does not explicitly speak about this, in fact the PEP 8 imports section is relatively small. I was wondering what the best practices were when importing using abbreviations.
For example:
import pandas as pd
import numpy as np
Are easily understood because they are very widely used packages. For my own case, I may have some obscure classes or functions in a module that I wish to import like:
from my_module import my_fun_function as mff
...
myvar = mff(input1)
versus
from my_module import my_fun_function
...
myvar = my_fun_function(input1)
Is there a best practices reference on this?
As you said. If the module is widely used it's acceptable to use abbreviations. If you have your custom module it is still okay to use abbrevation for it's name as long as it's well documented, clear and also widely used in code. Do not abbrevate if it's used just a couple of times.
However I would advise not to shorten function names as it feels like code obfuscation. I feel like ThisFunctionDoesThatThing(x) is way better than TFDTT(x).
I think it depends on your audience. If your audience is familiar with the function you are abbreviating or if you providing documentation for the function, then it certainly can make code more readable. However, if you abbreviate every single obscure function you import (even if you only use it once), then it becomes significantly less readable and a pain to understand.
There are no standards, for the aliases, although some are well accepted.
Keeping the alias short looks good most of the time, but is not the only option.

Why there is no end 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
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.)

Difference Between C and Python Ternary Operators [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
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.

Python: Is exec always bad practice and if so why not deprecated [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
Can someone think of an example with good practice that uses exec?
If there is always a more efficient and secure way to replace exec, why python doesn't deprecate exec?
As explained in other questions, eval/exec are considered bad practice because they're generally abused to do a task where they aren't needed, leading to potential security issues and generally bad programming.
There are, however, valid uses for these mechanisms, and they expose important functionality that is not available elsewhere - executing arbitrary code at runtime.
Imagine, for example, that you want write a application that updates itself. You could fetch a script from a remote URL that runs with exec and updates your application to the latest version. While doing something like that, by itself, would pose a great security hazard, it's not hard to make the process secure through the use of digital signatures.
You can find another common use in the code module source: executing code input from the user at runtime for debugging purposes.
No, eval and related tools are not always bad by any measure.
There are a number of things that only work well when they are expressed as regular functions with regular, positional or keyword arguments (not magic *args or **keywords args). There's no way to dynamically create a function with a desired set of arguments, except with eval.
For a good example of how this can be used, examine the implementation of collections.namedtuple. Although it would be possible to create a class factory like that without eval, but all of the functions it defines, __new__ and _replace in particular, would have useless help text, and would be a less convenient tool without it. Worse, the non-eval implementation would almost certainly be SLOWER.
Another, more sweeping example of this exact use of eval is the fine decorator library, which generalizes this practice in a collection of tools that allow you to dynamically create functions with particular function signatures; it uses eval internally.

Categories