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 10 months ago.
Improve this question
As far as I know, it is usually considered good to extract most strings to constant variables and avoid having "magic" strings and numbers in the middle of code. But in the Python world I have seen Exceptions raised with an string literal most of the time. I have also seen the same done in logging statements, and other similar situations.
Example of raising an Exception with a constant:
ARGUMENT_LIST_TOO_SHORT = "The provided list is too short"
def whatever_function():
raise ValueError(ARGUMENT_LIST_TOO_SHORT)
Example of raising an Exception with a string literal:
def whatever_function():
raise ValueError("The provided list is too short")
As I see it, it shouldn't be too bad if the string is only used once, as the risk of mistyping it is the same as typing it in the constant in the first place.
So is it a good practice to extract error description strings and log strings into constants? Or is it more Pythonic to use string literals?
Think about what you would need to do if you were writing code that was to be executed in a locale where the language didn't match the fixed text. As far as I know, Python doesn't having any out-of-the-box concept of a "resource bundle" (unlike Java for example).
This is a matter of opinion but I would argue strongly in favour of saying that text the user sees/interacts with should always be referenced indirectly. Such a technique facilitates re-use and language portability.
Having said that, the original question (and definitely this answer) are opinion based and therefore frowned upon in this forum.
Related
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 4 years ago.
Improve this question
is it a good practice that i usually (tend to) do in python?
making shortcut of functions for example:
p = print
and the i use:
p('hello world')
or
p(2**5)
does it affect on performance? What is your suggestion, is it OK?
A good practice in Python is: easy is better. You do not give much clarity in your code by doing that (and depending on the IDE-highlighting strategy, make it even worse for others). Furthermore, the choice of your shortcut, namely p, is really a bad idea. How about people writing code with prime numbers (and P is not a good idea too).
For performances, there is no gain I think. Since print is a built-in function, you actually add a variable inside globals() or locals(). In my opinion, this is 1) not a good practice to use shortcuts like that 2) not an improvement in performance.
I have no idea if it is a good practice in python, but in general I would say no.
It will take away readability for other readers of your code. If the codebase grows large and you replace a lot of functions with very short names you make it difficult to read in general.
Coming from many years of code maintenance if I was called out in the middle of the night to fix a code problem in production and found code like that I am pretty sure I would hunt you down in the morning and ask why you would ever do such a thing.
If you are lazy and doesn't want to write so much - get your self an editor that can complete code for you instead.
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
I read PEP8, and abbreviations for python, and I have question regarding the variable name itself.
I'm familiar with the famous variable abbreviations, For example, :
str for string
cnt for counter
cfg for configuration
It's came into my mind after thought about an appropriate name for a variable that contain first instruction, I thought about fisr_inst or first_instr or even first_instruction but couldn't find any document regarding this in Python.
but is there a table, or a list of all those abbreviation conventions in python? did I miss it?
EDIT - I didn't asked for appropriate name for "my variable name", I asked if there a table or list that contain some abbreviation for common use in python
Explicit and verbose is the recommended standard as far as naming things is concerned. EXTREMELY common abbreviations that are impossible to be mistaken are used to shorten line length, but don't think too far into those.
i for index, j for secondary index (in a 2D array), f for file, del for delete, str for string, cnt for count, cfg for config, prod for production, dist for distribution, fact for factorial, etc.
I don't know what use you have for first_instruction, but I wouldn't try to shorten either word - that is a solid variable name.
edit: My opinion has changed on the matter so I figured I'd share. I've now worked on distributed teams where contributing members have learned English later or are still learning English. Nowadays, I simply never abbreviate because I was only doing it to cut a few characters anyways 🤷♂️
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 6 years ago.
Improve this question
For example, would it be okay to use "pd" instead of "pandas" and "df" instead of "data_frame" in Python code?
On the one hand, using short variable names (less than 3 characters in length) is generally bad practice, stylistically, and from a maintainability perspective.
On the other hand, df and pd are rather ubiquitous for any Python programmer that uses the Pandas library.
What say you?
Stack Overflow really isn't the place for questions like this, may I suggest the Programmers Stack Exchange?
But since it is here, speaking as someone who has been forced to work with a massive C codebase with lots of 1-3 letter variable names and no documentation for the last few months, more verbose and descriptive variable names are probably better, especially if other people have to work with your code.
It would be better practice to use more letters, because if other people review your code, the variable pd would not make sense to them.
No, unless it's longer than 7 or 8 characters, as a rule of thumb. Get a proper IDE that can do some decent autocomplete, like PyCharm (autocomplete dialog automatically pops up and enter completes the variable).
df is too cryptic. Take a look at C++, with all its cryptic names itoa, itoa, stoi, etc.
PyCharm can do variable/class/function renaming automatically too.
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 6 years ago.
Improve this question
In python, is there a section of a PEP against the method __str__ returning a multiline string?
Pro: PyCharm does not tell me off and Google draws a blank
Contra: I could see it would cause an inelegant response if someone concatenated it, feels un-pythonic and I am not sure I can recall seeing one —bar in my own code
So I am not sure if to just have a multiline __str__ return (keep it simple) or to leave alone __str__ (i.e. returns <class foo>) and have a special module (e.g. foo.report()).
There's nothing wrong with it. There are plenty of classes that return multiline values for str (such as pandas DataFrames and Series). You can return whatever format you think best represents the object.
The __str__ method is meant to return a string value that is human readable. If there is any use in having multiple lines for that (such as the string representation of a board game that has two dimensions), you should do that. If it is meant to be consumed by another source, you may want to use a custom method that includes the appropriate information in the appropriate format, or override __repr__, which is meant to return an unambiguous string representation.
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
I am currently learning python and have been struggling learning new functions. There always seems to be a perfect match for functions I need and I never think of them until I see them utilized elsewhere. Is this normal? Does it happen to veteran programmers as well?
for example this snippet in learnpythonthehardway:
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
I would have never thought of doing that without going in circles first.
Do you have specific mnemonic techniques for memorizing stuff? Can anyone share their insights?
Write code. Firstly, you will eventually memorise the common built-ins, like len, range, etc. There are probably a few that you will never remember at once, these are those you hardly ever use (eval, exec, compile, etc.) but that will depend on the kind of programs you are writing. That is normal when learning a programming language.
Importantly, learn how to find your way around the documentation. You might not memorise the exact argument-list for each function, but you should know the kind of features that are available, and how to look it up.
The standard library modules are another matter. You might only use 10% of them, although some people will use considerably more. Again, only learn what you need, maybe start at aspects of sys. Even so, there are obscure corners of sys that you might never need.
Don't try to remember everything, you don't need to.
Write code.
Just practice I guess.
Also, when doing something that seems "common", check the doc: https://docs.python.org/3/. Like if you want to split strings etc...
It's a pitty there is nothing like Hoogle (for Haskell) in Python (AFAIK)