Search code examples
pythonrestructuredtext

How get Type of attribute from reStructuredText?


How get Type of attribute from reStructuredText? I have something like this.

@property
def port(self):
    """Get port.

    :return: port
    :rtype: str
    """
    return self._port

How can i get type of attribute (str)?


Solution

  • Is the code fragment yours? If yes, you can use whatever mechanics you like, e.g. add an attribute directly to the function for later inspection: SomeClass.port.fget.return_type = int. Try it, it works. Only be careful to qualify the property via the class, not via the instance (or use .__class__ on an instance).

    If not, parse the port.__doc__ and extract the relevant field.

    If you are CPU-constrained, you can still use e.g. SQLAlchemy without the ORM layer. It can produce very efficient SQL from table models ahead of time, e.g. during startup. Then you just invoke them with right parameters, paying rather little CPU time. In most cases, the DB round-trip dwarfs the query creation and results decoding anyway.

    Same applies to parsing the RST: you can do it ahead of time, e.g. as a build step, and store the information in an easy-to-parse file, e.g. JSON or even as pickled Python data, and quickly load it as startup.