caasswa
caasswa

Reputation: 521

Create a class with static functions? - Python

I need to have this import specifically in the class to prevent my tests having to include the imports for each test (they can't be declared outside because of circular dependency issues with the entire codebase).

I am trying to declare my imports in a class, and access what I need with functions but not too sure how to make this work so that any test can call the functions and get what we need.

I have this at the moment:

class KTestHelper:
    """ Small helper class for retrieving our hook and constants"""
    from fd.fdee import (
        IMOLDER,
        KDER,
    )

    p3 = P3Hook()

    @staticmethod
    def get_imolder(self) -> str:
        return self.IMOLDER

    @staticmethod
    def get_kder(self) -> str:
        return self.KDER

    @staticmethod
    def get_p3_hook(self) -> P3Hook:
        return self.p3

self obviously no longer exists as i added @staticmethod but now i'm not sure how to get it to work properly.

I need to be able to do KTestHelper.get_imolder() on every test function / some test functions that need it.

Upvotes: 1

Views: 117

Answers (1)

flakes
flakes

Reputation: 23644

This strategy isn't enough to prevent the module import. The class will be constructed during the module load and the class attributes get evaluated. Example:

test/
  __init__.py
  a.py
  b.py
c.py

a.py

print("loading module a")

class A:
    pass

b.py

print("loading module b")

class B:
    from .a import A

c.py

from test.b import B

This will output:

loading module b
loading module a

If you want this to work you'll need to put the import line in the class methods themselves.

print("loading module b")

class B:
    @classmethod
    def a(cls):
        from .a import A
        return A

Upvotes: 2

Related Questions