0

Does anyone have the similar experience to print assigned information for different objects? For instance, the following docstring printed from getattr(obj,'__doc__')

__doc__

Keyword arguments
-----------------
name : str
     (default "")
description : str
     (default "")
_id : str
     (default "")
script : str
     (default "")
dependencies : List[Dependency]
cyclic : bool
     (default False)
feature : str
     (default "")
index : int
  (default -1)

or set it in a variable docstr as docstr = '\n Keyword arguments\n -----------------\n name : str\n (default "")\n description : str\n (default "")\n _id : str\n (default "")\n script : str\n (default "")\n dependencies : List[Dependency]\n cyclic : bool\n (default False)\n feature : str\n (default "")\n index : int\n (default -1)\n '

is to be converted to:

adict = {'name' : str,
         'description' : str,
         '_id' : str,
         'script' : str,
         'dependencies' : List[Dependency],
         'cyclic' : bool,
         'feature' : str,
         'index' : int,
        }
MathArt
  • 159
  • 7
  • 1
    It might be easier and less error-prone to get this straight from the function [signature](https://docs.python.org/3/library/inspect.html#inspect.signature), rather than its docstring. – Thomas Nov 10 '22 at 11:39
  • A docstring [can have complex formatting](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#docstring-sections) and also complex types. It's purpose is to be read (usually also to generate documentation from it) so there's not much point in trying to convert a docstring (the [builtin `help`](https://stackoverflow.com/a/28698655) does print it). You may be thinking about [`__annotations__`](https://docs.python.org/3/howto/annotations.html?highlight=__annotations__) but that's also its own thing. The whole point is avoiding what you're trying to do. – bad_coder Nov 15 '22 at 17:56

1 Answers1

0

While waiting for answer, I figured one regex solution which at least can work for the current purpose.

s = '\n    Keyword arguments\n    -----------------\n    name : str\n         (default "")\n    description : str\n         (default "")\n    _id : str\n         (default "")\n    script : str\n         (default "")\n    dependencies : List[Dependency]\n    cyclic : bool\n         (default False)\n    feature : str\n         (default "")\n    index : int\n         (default -1)\n    '
keys = re.findall("(?<=\s)_?[a-z]+(?=\s:)", s)
vals = re.findall("(?<=:\s)\w+", s)
pair = {a:b for a, b in zip(keys, vals)}
MathArt
  • 159
  • 7