Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import only a class static method

Tags:

I have the following decorator in a base class:

class BaseTests(TestCase):     @staticmethod     def check_time(self, fn):         @wraps(fn)         def test_wrapper(*args,**kwargs):             # do checks ...         return test_wrapper 

And the following class inheriting from BaseTests:

from path.base_posting import BaseTests from path.base_posting.BaseTests import check_time  # THIS LINE DOES NOT WORK!  class SpecificTest(BaseTests):      @check_time # use the decorator     def test_post(self):         # do testing ... 

I would like to use the decorator in SpecificTest as above, without having to use BaseTests.check_time, because in the original code they have long names, and I have to use it in many places. Any ideas?

EDIT: I decided to make check_time an independent function in BaseTests file, and simply import

from path.base_posting import BaseTests, check_time 
like image 427
Alex Avatar asked Sep 26 '12 14:09

Alex


People also ask

Can you import a static method?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.

Can you import a static method in Java?

In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.

Why static imports are not good?

If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from.


1 Answers

Simply put

check_time = BaseTests.check_time 

in your second module:


from module_paths.base_posting import BaseTests check_time = BaseTests.check_time  class SpecificTest(BaseTests):      @check_time # use the decorator     def test_post(self):         # do testing ... 

You may also want to reconsider making check_time a staticmethod, since it appears your use case employs it more as a stand-alone function than as a staticmethod.

like image 148
unutbu Avatar answered Dec 07 '22 23:12

unutbu