python - should I use static methods or top-level functions

2024/11/19 1:46:20

I come from a Java background and I'm new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated with reading, some with writing. While searching for the correct approach, I saw this: Static methods in Python?

He mentions in his answer:

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

I don't understand top-level functions very well and I'm not sure given this simple example which is better: 1) create a class for a reader with static reader functions and the same for a writer or 2) to declare these helpers as global functions and why?

EDIT: REALLY good article about this subject i just found http://tomayko.com/writings/the-static-method-thing

Answer

In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated).

Python here begs to differ; if you have functions that don't have some shared state1 (and thus in Java would typically be static functions) and aren't tightly related to a "real" class (=one that is actually instantiated) you just use free functions inside a module.

The reasoning behind this is that a class is needed only when you actually want to instantiate it, thus having a class just as a container for several functions that don't need to share an instance-specific state is useless.

Actually, you can somewhat think of a module as a static class - i.e. a container of functions (=static methods), module variables (=static fields) and types.

The nice thing in Python is that having top-level function doesn't give global namespace pollution problems, since in Python top-level functions/objects/... are still module-scoped. Thus, you can still group functions by module, without the unnecessary class-tax.


  1. actually, they can have some shared state, in form of module-level variables (so, singletons); again, the analogy modules-static classes seems to hold.
https://en.xdnf.cn/q/26494.html

Related Q&A

Draw graph in NetworkX

Im trying to draw any graph in NetworkX, but get nothing, not even errors:import networkx as nx import matplotlib.pyplot as plt g1=nx.petersen_graph() nx.draw(g1)

Django 1.7 migrations wont recreate a dropped table, why?

Using Django 1.7 migrations.I accidentally dropped a table in my database. I assumed that by running migration again this would recreate the table but no, Django states "No migrations to apply&quo…

Reset ipython kernel

I was wondering if there is a way to restart the ipython kernel without closing it, like the kernel restart function that exists in the notebook. I tried %reset but that doesnt seem to clear the import…

What is the best way to remove a dictionary item by value in python? [duplicate]

This question already has answers here:Removing entries from a dictionary based on values(4 answers)Closed 4 years ago.I wonder if there is simple way to remove one or more dictionary element(s) from a…

How do I run a Python script on my web server?

Ive just started learning Python, and Im pretty lost right now. I want to run my script on my server that is hosted through hosting24.com. Their FAQ says they support Python, but I have no clue where t…

How to create an OrderedDict in Python?

I tried to maintain the order of a Python dictionary, since native dict doesnt have any order to it. Many answers in SE suggested using OrderedDict.from collections import OrderedDictdomain1 = { "…

How to log error to file, and not fail on exception

I am downloading a file from the net, and it fails even though I am doing: for p in query:try:except IOError as e:print e;If there is an error, I want to log it, and then continue on with the next file…

Suggestions for Python debugging tools? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site …

How can you bundle all your python code into a single zip file?

It would be convenient when distributing applications to combine all of the eggs into a single zip file so that all you need to distribute is a single zip file and an executable (some custom binary tha…

Pass Variable On Import

Lets say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is load…