Alberto B
Alberto B

Reputation: 541

import method from current module

I would like to import a method in the same module where it is defined like this:

def method1():
    print('1')


def method2():
    print('2')


boolean = True
if boolean:
    from __file__?? import method1 as method
else:
    from __file__?? import method2 as method

method()

is this somehow possible?

and what if all this is inside a class:

class MyClass():
    def __init__(self):
        boolean = True
        if boolean:
            from MyClass?? import method1 as method
        else:
            from MyClass?? import method2 as method

        method()
    
    @staticmethod
    def method1():
        print('1')

    @staticmethod
    def method2():
        print('2')

is this somehow possible? or what is a workaround to achieve the same thing? I already tried using partial from functools but it slows down quite a bit

EDIT: many thanks for all your answers, I didn't know I could assign a method to a variable

Upvotes: 0

Views: 71

Answers (1)

Matteo Zanoni
Matteo Zanoni

Reputation: 4142

As suggested in the comments you do not need to import a method that is defined in the same file. So your solution would be to just:

def method1():
    print('1')


def method2():
    print('2')


boolean = True
if boolean:
    method = method1
else:
    method = method2

method()

And for the class:

class MyClass():
    def __init__(self):
        boolean = True
        if boolean:
            self.method = self.method1
        else:
            self.method = self.method1

        method()
    
    @staticmethod
    def method1():
        print('1')

    @staticmethod
    def method2():
        print('2')

Upvotes: 1

Related Questions