1

As I try to use more and more functional programming (i.e. use classes less), I have noticed I start to use modules as classes:

#File foomod.py

foo = None

def get_foo():
    global foo
    if foo is None:
        foo = 1 + 1
    return foo

# main.py

import foomod
x = foomod.get_foo()

This might as well be

#File foo.py

class foo:
    foo = None

    @staticmethod
    def get_foo(cls):
        if cls.foo is None:
            cls.foo = 1 + 1
        return cls.foo

# main.py

from foo import Foo
x = Foo.get_foo()

Is there any reason to favour one over the other? E.g. speed or something else?

run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • What is the intended purpose of the class? – khelwood Jun 13 '22 at 14:19
  • It loads data from a bunch of files, only when required, and caches it so it is only required to be performed once. It's the `1+1` operation in the above example. – run_the_race Jun 13 '22 at 14:20
  • I can see the point of the `get_foo` function, but I can't see why you would put it in a class. – khelwood Jun 13 '22 at 14:22
  • I could use the @cache or @ lru_cache decorator in the above example, but its only one example. Its in a class because classes are basically function with state. The state is the result of the expensive operation. – run_the_race Jun 13 '22 at 14:23
  • I think this page will answer your question https://stackoverflow.com/questions/33072570/when-should-i-be-using-classes-in-python – R C N Jun 13 '22 at 14:28

0 Answers0