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.
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 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.
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'm writing a module which only contains functions. Is it good practice to put these inside a class, even if there are no class arguments and the __init__ function is pointless? And if so how should I write it?
There's no particular reason to force functions to go inside a class if there's no reason to make a class. A python sourcefile already provide a perfectly reasonable namespace for storing similar, related functions. The pypy implementation of the python programming language, for example, has many modules that don't have classes in them (for example, time).
You would want a certain data structure as a class, of course, but there are certain behaviors that are entirely independent of data structures, and putting them in a class would just add needless complexity.
It is good to build modules that contain a class for better organization and manipulation depending on how big the code is and how it will be used, but yes it is good to get use to building classes with methods in them. Can you post your 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 3 years ago.
Improve this question
please I want to know a way to remember or to easy difference between using
v.function() or function(v) in python # v is a variable or object
capitalize(c) #error
c.capitalize() # OK
c="hello"
c.capitalize()
The first version calls a function with v as an argument, the second one calls a method of the object v. Which one it is in a particular case may vary depending on the design approach, but in general:
1) If it modifies the state of an object, it's likely a method.
Examples: list.sort(), dict.pop().
2) If it works on a variety of similar types, e.g. on containers, it's likely a function.
Examples: len(), sum(), sorted().
3) If it object type specific and has to know something about the object implementation internals, it's likely a method.
Examples: str.capitalize(), str.split().
4) If in doubt - refer to the documentation.
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 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
Implementation of the algorithm in Wiki article has a drawback.
If the tree consists from only one root then nothing happen. The tree is not
modified. How to fix this issue? In C++ it is possible to set root pointer to null, but what to do in python?
This is a continuation of a previous question, and the OP is looking to replace the value with None, but for all names that have that instance assigned to them - this is not possible in Python.
The answer is there is no way to delete the value in this case due to the way Python is designed - you would have to implement an object manager of some kind, store it in a container and access it through that, or change your design not to rely on mutation.
Another question worth asking - is this a case that is likely to happen? It may be possible (and desirable) just to define this as a limitation where the root node can't be destroyed. I can't think of a case where you would want that functionality.