Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method vs module function in python

So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the class).

Is there any benefit for doing it either way? The class is being imported by from module import class so I'm not worried about having those modules pulled in as well. But should I just make them class methods so that from module import * is safer or something?

like image 429
Falmarri Avatar asked Aug 25 '10 22:08

Falmarri


People also ask

When should I use static method in Python?

Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.

What is the difference between static method and class method in Python?

Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.

What is a static method in Python?

What is a static method? Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.

Is Staticmethod faster Python?

It looks like staticmethod is slightly faster (likely just because it doesn't need to pass an argument into the function at all), but we're talking about a difference of 3 milliseconds for 100,000 calls, which is nanoseconds per call in cost.


2 Answers

Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *.

Another technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__.py file)

__all__ = ['my_class_name']

This is more of a whitelist approach, so you can have full control over what gets imported without using leading underscores.

So unless your methods logically belong in the class, and from your description they don't, I would leave them as module level functions and use one of these two approaches to make them private.

like image 86
Scott Griffiths Avatar answered Sep 28 '22 06:09

Scott Griffiths


Make them module-level functions, and prefix them with a single underscore so that consumers understand that they are for private use.

like image 41
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 05:09

Ignacio Vazquez-Abrams