1

I have a Python project where most business logic is in class methods. Now I would like to reuse some of the class methods in an independent project.

Is it possible to write a class method that 'exports' other class methods to a new Python file to create a script with a bunch of exported functions?

class MyObject:

    def __init__(self, value):
        self.value = value

    def method1(self):
        # the method I want to use in another project

    def method2(self):
        ...

    def method3(self):
        ...

    def export_method(self, target_file):
        # export the code of method1 to a new python file

When I run export_method('myfile.py') I would like to create a Python file that contains method1 as a function:

def method1():
    ...

Note: I understand that the software should be restructured and method1 should be in another module where it can be imported from other projects. I'm just curious if there is a simple way to access the code of a Python program from the code itself.

Martin Preusse
  • 9,151
  • 12
  • 48
  • 80
  • 1
    and what if one of those exported methods uses `self.value` in its body? oops? – RomanPerekhrest Oct 09 '19 at 18:35
  • What do you mean by "export the code to another python file" **exactly**? – juanpa.arrivillaga Oct 09 '19 at 18:35
  • Possible duplicate of [How can I get the source code of a Python function?](https://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function) – glibdud Oct 09 '19 at 18:44
  • @RomanPerekhrest I know it does not work. Still a valid question though. Maybe there is a way to transform `self.var` calls to function arguments and get `method1(value, other_argument)`? – Martin Preusse Oct 09 '19 at 19:35

1 Answers1

0

Use inspect:

Either directly:

import inspect
lines = inspect.getsource(MyObject.method1)
with open(target_file, 'w') as file:
    file.write(lines)

Or if you prefer to get it as a class method and print all methods in the class:

import inspect

class MyObject:

    def __init__(self, value):
        self.value = value

    def method1(self):
        pass

    def method2(self):
        pass

    def method3(self):
        pass

    @classmethod
    def export_method(cls, target_file):
        # export the code of method1 to a new python file
        methods = inspect.getmembers(cls, predicate=inspect.ismethod)
        with open(target_file, 'w') as f:
            for method in methods:
                lines = inspect.getsource(method[1])
                f.write(lines)

Because of the @classmethod decorator the following is allowed:

MyObject.export_method('code.txt')
b3rt0
  • 769
  • 2
  • 6
  • 21