What is the preferred Python 3.x class definition syntax? [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 8 years ago.
Improve this question
As Is it necessary or useful to inherit from python's object in Python 3.x? and Python class inherits object make clear, it is no longer necessary to inherit from object when defining a class in Python 3.
As a corollary to this which isn't directly addressed by either of the linked questions: should I prefer either style over the other when writing new Python 3 code? Is it better to drop the object base class in the interest of cleaner class definitions, or leave it in in order to (potentially) make future ports to Python 2 easier?

Programming is converting the abstract ideas into a formal form that is later used to produce executable. There is no need to make the process more complex than neccessary. The machines were created to help us. It does not apply in the opposite direction.
In some sense, Python 3 is a new language. Then the question should be: "Should I force myself to use the new language so that it would look the way the old tools/programmers were used to?"
It's time again to read the Zen of Python one by one:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

pylint appears to still warn about not using object when defining a class in 3.x, so I also add it, even for 3.x-only code. I write a lot of Python that runs on both 2.x and 3.x; there it's a cinch that you want it.
But you make reasonable arguments for both sides, really. What do you think?

Related

is it a good practice in python? function shortcuts? [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 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.

Python inheritance - multiple superclasses [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 that a pythonic way to create a class that inherits from more than 10 classes? Or maybe I should consider a different approach?
it is allowed, you can also consider creating a composite object, an object that has other objects as it's members, instead of inheriting them.
wiki for the concept of composition: composition
multiple inheritance in python: multiple inheritance
these should help you understand, and then decide what is better for you in the context of your program.
Yes, inheriting from multiple classes in perfectly legal. However, if you have 10 super classes, it seems that you might need to tweak your inheritance tree. Perhaps some of the classes can be inherited by intermediate classes so that the final class inherits from fewer classes.
You should also learn about composition which might provide a cleaner solution for what you are trying to do.
Multiple inheritance is valid in Python but not used often. Most of usecases that I seen is mixins (small snippets mixed into a main heirarchy tree).
Creating a class with 10 parents is a bad smell in any OOP language and not pythonic at all. You should refactor you classes into another kind of abstraction.
Is that OK to inherit from many classes (more than 10) in Python?
It is "OK", in that Python will accept it and will not break or crash.
Is that a pythonic way to create a class or I should consider a different approach?
It is, most certainly, not a "pythonic" way to create a class. Having many parent classes only aggravates the well-known problems of having a few parent classes (diamond problem, etc.), plus it makes the class directly dependent on many others, and makes it very difficult to track down where each behavior in a class comes from. That goes against the general spirit of simplicity in Python (or good programming practices in general).
Note that making a class child of another one establishes an "is a" relationship. Is your class really all of those ten things? Or are you just inheriting to gain some of the already implemented behaviors? Look up some basic principles of object-oriented design such as SOLID, why sometimes we may prefer composition over inheritance, and alternative architectural patterns such as entity–component–system.

Can use of multiple naming conventions be consistent? [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 6 years ago.
Improve this question
I've been taught that while both camelCase and under_scores are acceptable variable names I need to be consistent in my approach.
How consistent is consistent though? Is it acceptable and Pythonic to use both under certain circumstances?
E.g. could I use camelCase for variables in my main code and under_scores for those in my functions? or perhaps one for variables which have answers derived from my own functions and one for other functions?
Both of these could be done in a way that makes it easy for those reading it to understand and follow basic systematical rules does that alone make it okay to use both or am I expected to follow through with only one naming convention?
Example of using under_scores for variables whose answer is derived from a user defined function and camelCase for other variales.
# My function.
def reverse(variableCalledA):
variableNamedB = reverseVariableA(variableCalledA) # {= 235}.
return variableNamedB
# Main code.
variableCalledA = 532
**reversed_variable_called_b** = reverse(variableCalledA)
answer = variableCalledA - **reversed_variable_called_b**
print(answer)
P.S. If this is appropriate than is it something I should mention in a comment so other users know to look out for it?
P.S.S. Please alert me to any ways I could update/improve my question and future questions.
Naming conventions are there to increase code clarity and make it easier for many developers to work on the same code base.
As such, the answer to your question really depends on the situation. If you are working in a professional setting you should adhere to whatever naming convention the company uses. If there is no existing naming convention, you should push for one. Generally, any new Python project should adhere to the PEP8 style guide, unless there's a good reason not to (for example: years of legacy code that uses a different style guide).
No matter if you are working on a new project or on legacy code, my personal opinion is that mixing camelCase and under_scores is just not a good idea. The example you provided sounds reasonable, but it is not a convention that other developers would know about unless it was explained in comments.
For being consistent you can use under_scores instead of camelCase as the former is more readable than the latter. You can see one of the posts on naming-convention here.
Is it acceptable and Pythonic to use both under certain circumstances?
Yes it is acceptable and pythonic to use both but under only certain circumstances. You can check PEP-8 guid for devs.
For function names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Certain circumstances include backward compatibility
mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
For Class names
Class names should normally use the CapWords convention.
The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.
Concluding, if you are building on top of some library it is better to go with the library style. For pythonic conventions PEP-8 is there to guide devs.
Is the code for yourself or a project you are working on with others? I think it is best to follow the style standards of the team. This way your team can follow your code.
When you write for yourself. Use the system that makes sense to you so that when you are reading the code a year from now you don't have to struggle.
PEP8 makes sense. CapWords for classes, UPPER_CASE for constants and names_with_underscores for everything else.
I put excessive comments in my code. Even with variables fully spelled out comments still help.
For people like me with CRS (Can't Remember Shit) long variable names help me remember what the variable holds, when I go back and look at the code.

Multiple inheritance in python vs composition [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 6 years ago.
Improve this question
I have a solid understanding of OOP and its idioms in Java.
Now I am coding in python, and I am in a situation where having multiple inheritance may be useful, however (and this may be due to years of java code), i am reluctant to do it and I am considering using composition instead of inheritance in order to avoid potential conflicts with potential equal method names.
Question is, am i being to strict or too java focused regarding this thing. Or using multiple inheritance in python is not only possible but also encouraged.
Thanks for your time :)
The question of "inheritance vs. composition" comes down to an attempt to solve the problem of reusable code. You don't want to have duplicated code all over your code, since that's not clean and efficient. Inheritance solves this problem by creating a mechanism for you to have implied features in base classes. Composition solves this by giving you modules and the ability to simply call functions in other classes.
If both solutions solve the problem of reuse, then which one is appropriate in which situations? The answer is incredibly subjective, but I'll give you my three guidelines for when to do which:
Avoid multiple inheritance at all costs, as it's too complex to be useful reliably. If you're stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from.
Use composition to package up code into modules that is used in many different unrelated places and situations.
Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept, or if you have to because of something you're using.
However, do not be a slave to these rules. The thing to remember about object oriented programming is that it is entirely a social convention programmers have created to package and share code. Because it's a social convention, but one that's codified in Python, you may be forced to avoid these rules because of the people you work with. In that case, find out how they use things and then just adapt to the situation.
More details can be found on: http://learnpythonthehardway.org/book/ex44.html
I would still prefer composition to inheritance, whether multiple or single. Really getting into duck typing is a bit like having loads of implicit interfaces everywhere, so you don't even need inheritance (or abstract classes) very much at all in Python. But that's prefer composition, not never use inheritance. If inheritance (even multiple) is a good fit and composition isn't, then use inheritance.

What are features considerd as advanced 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 2 years ago.
Improve this question
I do basic python programming and now I want to get deep into language features. I have collected/considered the following to be advanced python capabilities and learning them now.
Decorator
Iterator
Generator
Meta Class
Anything else to be added/considered to the above list?
First, this thread should be community wiki.
Second, iterators and generators are pretty basic Python IMHO. I agree with you on decorators and metaclasses. But I'm not a very good programmer, so I probably find this more difficult to wrap my brain around than others.
Third, I would add threading/multiprocessing to the list. That's really tricky :)
There are some useful core concepts that can be added to your list, and that I would not necessarily teach in an introductory Python class (from the most common to the more specific):
the various protocols (sequence, iterator, context,…)
properties
packages
Some points related to important standard modules:
Making your classes compatible with the standard copy and pickle modules.
The first 3 are intermediate Python, not advanced. For advanced add the stuff in the Importing Modules and Python Language Services sections of the library reference.
I think you'll find that there isn't a good answer to your question. What's great about Python is that all of its features are fairly easy to understand. But there's enough stuff in the language and the library that you never get around to learning it all. So it really boils down to which you've had occasion to use, and which you've only heard about.
If you haven't used decorators or generators, they sound advanced. But once you actually have to use them in a real-world situation, you'll realize that they're really quite simple, and wonder how you managed to live without them before.

Categories

Resources