I’m a python beginner, and is wondering what’s more pythonic way to write utility functions? As in Java/C++, create a utility class and have methods inside it or write functions inside the module? The function is to be used across various classes in the same module.
The same question for variables used by different classes and functions in the module. I can have them inside the utility class or have them defined inside the module. What is more pythonic? Someone please guide me.
The only argument I have in favor of writing them inside class is it makes it more objected oriented.
Welcome to Python! You’re a long way from C++ and Java, and that’s a good thing. 😉
This is an excerpt from an excellent discourse on object-oriented programming by another StackOverflow volunteer:
Quick: off the top of your head, what is object-oriented programming about?
If you thought any of the words “encapsulation”, “inheritance”, “polymorphism”, “information hiding”, “abstraction”, or “vtables”, you are wrong.
If you thought any of the words “class”, “prototype”, or “type”, you are still wrong.
Object-oriented programming is about objects: bundles of state and behavior.
Why am I quoting this? (Well, for one, it’s Pythonic to like expressive quips that you can get behind the message of.) Because therein lies the answer to your question.
Does your “utility function” actually represent some behavior that can be expressed nicely (key word) as the parent object in an inheritance heirarchy? Then by all means, put it in a class. But not if that means creating a class just to put it in.
You’re always participating in object-oriented programming when you’re writing Python, because everything in Python is an object. (Consider that you can even call methods on literals, e.g.,
'hello'.upper().) If you squint at it a certain way, you can think of even your modules as just being the inside of a class definition. They have their own scope, possibly module-level functions (module “methods” if you’re following my analogy), and possibly inner classes. The behavior is extremely similar because it’s essentially the same interface.
I suggest you have a look through your
site-packages directory at all the available modules and packages. You’ll get some really good ideas how this is normally done, and you’ll probably see dozens of examples of module-level functions that are more or less what you’re referring to when you say “utility function”.