0

I have this class in python defined like this

class MyClass(object):
   @property
   def property1(self):
       # type: () -> pb.data.Property1

   @property
   def property2(self):
       # type: () -> pb.data.Property2

How can I use reflection to read all the properties that the class has and then make a map from the property name to its class

something like

{"property1":"pb.data.Property1", "property2":"pb.data.Property2"}

Remember that the first line in each property is a comment. Is there a clear way to do it?

rajan sthapit
  • 4,194
  • 10
  • 42
  • 66
  • Why comments? Turn them into docstrings. – bipll Apr 15 '18 at 05:36
  • @bipll. They are kind of autogenerated. I can't change them – rajan sthapit Apr 15 '18 at 05:38
  • Autogenerated with what? You can modify the autogeneration tool to put annotations in a more pythonic way, you can add one more phase to code generation to turn comments into strings, you can do it manually per each source file under your control, what have you tried before admitting "I can't"? – bipll Apr 15 '18 at 07:56
  • 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) – bipll Apr 15 '18 at 08:00

1 Answers1

0

You can use inspect.getmembers to get all the attribute values. Hopefully below code will help you out.

import inspect
class MyClass(object):
    @property
    def property1(self):
        return 'pb.data.Property1'

    @property
    def property2(self):
        return 'pb.data.Property2'

    def get_attributes(self):
        attributes = inspect.getmembers(self, predicate=lambda a: not(inspect.isroutine(a)))
        return {d[0]:d[1] for d in attributes if not(d[0].startswith('__') and d[0].endswith('__'))}


MyClass().get_attributes()

Output: {'property1': 'pb.data.Property1', 'property2': 'pb.data.Property2'}

atiq1589
  • 2,227
  • 1
  • 16
  • 24