1

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.

caasswa
  • 501
  • 3
  • 10
  • so the answer is to use classmethod instead? what are the differences between classmethod and staticmethod? – caasswa Dec 08 '21 at 13:05
  • 1
    https://stackoverflow.com/search?q=%5Bpython%5D+classmethod+staticmethod – mkrieger1 Dec 08 '21 at 13:06
  • hmm, i don't want the p3 hook to be reinstantiated every time someone calls `KTestHelper`, so would classmethod be the right thing here? – caasswa Dec 08 '21 at 13:08
  • `p3 = P3Hook()` is executed once when the class is created. This has nothing to do with static methods or class methods. – mkrieger1 Dec 08 '21 at 13:10
  • Thank you, begs the question if one needs to put classmethod or staticmethod at all, but i guess you'd have to otherwise you'd have to create a new `KTestHelper` object every time in each function that needs it – caasswa Dec 08 '21 at 13:15
  • Voting to reopen. The linked issue is not the crux of the problem. – flakes Dec 08 '21 at 13:18
  • Thanks flakes... i think i got downvoted with the thought that it was similar but didn't quite feel it was! – caasswa Dec 08 '21 at 14:31

1 Answers1

2

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
flakes
  • 21,558
  • 8
  • 41
  • 88