diff options
author | cpopa <devnull@localhost> | 2013-09-22 23:27:55 +0300 |
---|---|---|
committer | cpopa <devnull@localhost> | 2013-09-22 23:27:55 +0300 |
commit | 5ae9fd56321d2c81a440aa440fc505b79d4300cb (patch) | |
tree | 0330eee7d110f8250dc9f5956b613afc0be883cc /checkers/utils.py | |
parent | edcddebadd990e43a30f7a07b8efca0a02646964 (diff) | |
download | pylint-5ae9fd56321d2c81a440aa440fc505b79d4300cb.tar.gz |
Add basic checks for Python 3 format strings.
Diffstat (limited to 'checkers/utils.py')
-rw-r--r-- | checkers/utils.py | 35 |
1 files changed, 34 insertions, 1 deletions
diff --git a/checkers/utils.py b/checkers/utils.py index 68b5469..119a859 100644 --- a/checkers/utils.py +++ b/checkers/utils.py @@ -26,9 +26,13 @@ from astroid import scoped_nodes from logilab.common.compat import builtins BUILTINS_NAME = builtins.__name__ - COMP_NODE_TYPES = astroid.ListComp, astroid.SetComp, astroid.DictComp, astroid.GenExpr +if hasattr(string, 'Formatter'): + STRING_FORMATTER = string.Formatter() +else: + STRING_FORMATTER = None + class NoSuchArgumentError(Exception): pass @@ -346,6 +350,35 @@ def parse_format_string(format_string): i += 1 return keys, num_args +def parse_format_method_string(format_string): + """Parses a Python 3 format string, returning a tuple of (keys, num_args), + where keys is the set of mapping keys in the format string, and num_args + is the number of arguments required by the format string. + """ + keys = set() + num_args = 0 + + # TODO: should raise a custom exception? + if not STRING_FORMATTER: + return keys, num_args + + parseiterator = STRING_FORMATTER.parse(format_string) + try: + for result in parseiterator: + if all(item is None for item in result[1:]): + # not a replacement format + continue + name = result[1] + if name: + keys.add(name) + else: + num_args += 1 + except ValueError: + # probably the format string is invalid + # should we check the argument of the ValueError? + raise IncompleteFormatString(format_string) + return keys, num_args + def is_attr_protected(attrname): """return True if attribute name is protected (start with _ and some other details), False otherwise. |