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?
Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.
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? 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.
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.
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.
Make them module-level functions, and prefix them with a single underscore so that consumers understand that they are for private use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With