How can I extract keywords from a Python format string?

前端 未结 4 1684
梦谈多话
梦谈多话 2020-11-29 06:13

I want to provide automatic string formatting in an API such that:

my_api(\"path/to/{self.category}/{self.name}\", ...)

can be replaced wit

4条回答
  •  Happy的楠姐
    2020-11-29 06:49

    If all placeholders are named, a special dictionary could be used to intercept which keys are tried to be accessed and logged to an array.

    def format_keys(str_):
        class HelperDict(dict):
            def __init__(self):
                self._keys = []
            def __getitem__(self, key):
                self._keys.append(key)    
        d = HelperDict()
        str_.format_map(d)
        return d._keys
    

    Note that if there are unnamed placeholders, an IndexError will be raised by .format() (tuple index out of range).

提交回复
热议问题