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.

7
  • so the answer is to use classmethod instead? what are the differences between classmethod and staticmethod? Commented Dec 8, 2021 at 13:05
  • 1
    stackoverflow.com/… Commented Dec 8, 2021 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? Commented Dec 8, 2021 at 13:08
  • p3 = P3Hook() is executed once when the class is created. This has nothing to do with static methods or class methods. Commented Dec 8, 2021 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 Commented Dec 8, 2021 at 13:15

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I see! That is a good observation - very important. I'll give that a try

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.