8

i want to import some function in a class without needing to import the whole class.

I have some class as follows


MyClassFile.py

class MyClass: def __init__(self): pass #Some init stuff def some_funcs(self): pass #Some other funcs @staticmethod def desired_func(): pass #The func i want to import 

MyScript.py

from MyClassFile import MyClass.desired_func 

or

from MyClassFile.MyClass import desired_func 

I tried to import that way but isn't work, is there any way to do it?

15
  • Hi Ivan, what's your reason for not wanting to import the class? Commented Jan 9, 2018 at 23:14
  • 4
    There is no way to do it in one import statement. When would that be useful? If it's a static method, make it a standalone function. Commented Jan 9, 2018 at 23:14
  • 1
    @Miket25 That doesn't seem to be asking the same question. This is asking about using import to access attributes of a class, which is not a factor in the question you linked. Commented Jan 9, 2018 at 23:19
  • @DavidZ The question asks how do you import some function of a class and have its use available in another file. The question I linked with the accepted answer points to that it's not possible to link attributes of a class, being the methods. Can you please explain what's different; I'm not sure if I get your difference? Commented Jan 9, 2018 at 23:23
  • @Ajax123 why did you reopen this question? Commented Jan 9, 2018 at 23:27

1 Answer 1

12

To play devil's advocate:

# MyScript.py desired_func = __import__('MyClassFile').MyClass.desired_func 

On a more serious note, it sounds like your staticmethod should actually just be a module level function. Python is not Java.

If you insist on having a staticmethod, pick one of the options below:

  1. Import the class as usual and then bind a local function: f = MyClass.desired_func
  2. In MyClassFile.py, after the class definition block, alias a module-level function to the staticmethod and then import that name directly.
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, this works. I will search more about module level function, thank you
@IvanGonzalez While it works, this backdoor use of __import__ should be discouraged.
@IvanGonzalez don't do this... wim was being funny

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.