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
As the title suggests, I'm interested in the best (perhaps the most Pythonic way) to structure a program which uses many global variables.
First of all, by "many", I mean some 30 variables (which may be dictionaries, floats or strings) which every module of my program needs to access. Now, there seem to be two ways to do this:
define the "global" variables in seperate modules
use an object oriented approach
The advantage of using an object oriented approach is that I can have many instances of some main class initialized, and perhaps compare different values (results of some analysis, for example) later on.
I already have a program written, but basically it breaks down to one class with some 30 or so attributes. Although it works fine, I'm aware this is a pretty messy way to do this.
So, basically, is I use OOP approach, I would perhaps need to break my main class down to a few subclasses, every one of which stores specific logically related variables.
Any suggestions are welcome.
P.S. Just to be concrete about what I'm trying to do: I have a FEM-solver which needs to store structure info, element and node data, analysis result data, etc. So, I'm dealing with a lot of data types most of which are connected in some way.
Unfortunately, as was hinted at in the comments, there is no "Pythonic" way to do this. Having a large number of global constants is just fine - many programs and libraries do this. But in the comments, you've specified that all of your globals are being modified.
You need to take your program's architecture back to the drawing board. Rethink the relationships between your program's entities (functions, classes, modules, etc). There has to be a better way to organize it.
And by the way, it also sounds like you're getting close to using the God Object Antipattern. Use some of the advice in this SO question to refactor your massive class that has it's fingers all over your program.
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 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 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 am sure this question was already answered couple of times, and i will soon close this topic, but i couldn't find it.
Is there a recommendet way of arranging member functions?
I am pretty sure not everything need rules, but wanted to if there are thoughts about this topic, which goes more then sorting by access level.
Example class in Pseudocode:
Class
amethod()
bmethod()
cvariable
avariable
bvariable
There are some recommendations, but they are rather vague. The only common point is, quoting the Google Java Style Guide, § 3.4.2,
that each class order its members in some logical order, which its
maintainer could explain if asked. For example, new methods are not just
habitually added to the end of the class, as that would yield "chronological
by date added" ordering, which is not a logical ordering.
The Google C++ Style Guide recommends to order by visibility (which is obvious for C++), then by type:
Typedefs and Enums
Constants (static const data members)
Constructors
Destructor
Methods, including static methods
Data Members (except static const data members)
Oracle’s Code Conventions for Java, § 3.1.3, recommend to order by type, then by visibility (for variables) or functionality (for methods):
Class (static) variables (ordered by visibility)
Instance variables (ordered by visibility)
Constructors
Methods (grouped by functionality rather than by scope or accessibility)
I´m not aware of any generally/widely accepted convention, other than "use something that makes sense" (eg. grouping variables instead of writing a wild mix of vars and functions).
However, it´s not only a style question:
In C++ (and C), the order maps directly to the memory layout, this can lead to different variable sizes because of alignment and padding. Additionally, if serializing something in a binary format, where which value is in the data is of course important (but serializing that way is not exactly good, because the memory layout depends...).
And, like #huu noted in the comments, the variable order determines the initialization order, this is important a member variables is initialized with the value of another member variable (of the same object). A mismatch in variable declaration order and initialization order will lead to a compiler error.
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
Sometimes, when looking at Python code examples, I'll come across one where the whole program is contained within its own class, and almost every function of the program is actually a method of that class apart from a 'main' function.
Because it's a fairly new concept to me, I can't easily find an example even though I've seen it before, so I hope someone understands what I am referring to.
I know how classes can be used outside of the rest of a program's functions, but what is the advantage of using them in this way compared with having functions on their own?
Also, can/should a separate module with no function calls be structured using a class in this way?
A module is preferred when it is a collection of pure functions i.e. no shared state like module level variables. A big class is often used when there are multiple functions operating on a shared state.
In Python scripts, you will often see the pattern of the main function being just the instantiation of a class and calling a method for e.g youtube-dl. This is done for various reasons:
Can instantiate multiple objects without mixing state. It is easier to make it threadsafe.
Classes can be inherited or composed (for e.g. see BaseHTTPRequestHandler
Classes have more features than modules like constructors, iteration support etc.
In general, classes offer more power with slight added complexity. Some people prefer functions for simplicity esp in the case of one-time scripts. The tradeoff is upto the developer and both are valid options in Python.
A program often has to maintain state and share resources between functions (command line options, dB connection, etc). When that's the case a class is usually a better solution (wrt/ readability, testability and overall maintainability) than having to pass the whole context to every function or (worse) using global state.
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)
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.