user1276560
user1276560

Reputation: 135

How do I return the definition of a class in python?

Say I have a class "NumberStore"

class NumberStore(object):
    def __init__(self, num):
        self.num = num

    def get(self):
        return self.num

And later on, for the purpose of serialization, I want to print a definition of the class, either exactly as stated, or equivalently stated. Is there any way in python to access a class's definition as in the idealized example below?

>>> NumberStore.print_class_definition()
"class NumberStore(object):\n    def __init__(self, num):\n        self.num = num\n    \n    def get(self):\n        return self.num"

Upvotes: 1

Views: 212

Answers (2)

vaultah
vaultah

Reputation: 46533

Yep, with inspect.getsource:

from inspect import getsource

class NumberStore(object):
    def __init__(self, num):
        self.num = num

    def get(self):
        return self.num

    @classmethod
    def print_class_definition(cls):
        return getsource(cls)

Upvotes: 2

falsetru
falsetru

Reputation: 369054

Use inspect.getsource.

import inspect
source_text = inspect.getsource(NumberStore)

Upvotes: 1

Related Questions