Debian Codegraph @

ml_collections/config_flags/tuple_parser.py

raw symbols SCIP
1 # Copyright 2024 The ML Collections Authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """Custom parser to override tuples in the config dict."""
16 import ast
17 import collections.abc
18
19 from absl import flags
20
21
22 class TupleParser(flags.ArgumentParser):
23 """Parser for tuple arguments.
24
25 Custom flag parser for Tuple objects that is based on the existing parsers
26 in `absl.flags`. This parser can be used to read in and override tuple
27 arguments. It outputs a `tuple` object from an existing `tuple` or `str`.
28 The ony requirement is that the overriding parameter should be a `tuple`
29 as well. The overriding parameter can have a different number of elements
30 of different type than the original. For a detailed list of what `str`
31 arguments are supported for overriding, look at `ast.literal_eval` from the
32 Python Standard Library.
33 """
34
35 def parse(self, argument):
36 """Returns a `tuple` representing the input `argument`.
37
38 Args:
39 argument: The argument to be parsed. Valid types are `tuple` and
40 `str` or a single object. `str` arguments are parsed and converted to a
41 tuple, a single object is converted to a tuple of length 1, and an empty
42 `tuple` is returned for arguments `NoneType`.
43
44 Returns:
45 A `TupleType` representing the input argument as a `tuple`.
46 """
47 if isinstance(argument, tuple):
48 return argument
49 elif isinstance(argument, str):
50 return _convert_str_to_tuple(argument)
51 elif argument is None:
52 return ()
53 else:
54 return (argument,)
55
56 def flag_type(self):
57 return 'tuple'
58
59
60 def _convert_str_to_tuple(string):
61 """Function to convert a Python `str` object to a `tuple`.
62
63 Args:
64 string: The `str` to be converted.
65
66 Returns:
67 A `tuple` version of the string.
68
69 Raises:
70 ValueError: If the string is not a well formed `tuple`.
71 """
72 # literal_eval converts strings to int, tuple, list, float and dict,
73 # booleans and None. It can also handle nested tuples.
74 # It does not, however, handle elements of type set.
75 try:
76 value = ast.literal_eval(string)
77 except ValueError:
78 # A ValueError is raised by literal_eval if the string is not well
79 # formed. This is probably because string represents a single string
80 # element, e.g. string='abc', and a tuple of strings field was overridden by
81 # repeated use of a flag (ie `--flag a --flag b` instead of
82 # `--flag '("a", "b")'`).
83 value = string
84 except SyntaxError as exc:
85 # The only other error that may be raised is a `SyntaxError` because
86 # `literal_eval` calls the Python in-built `compile`. This error is
87 # caused by parsing issues.
88 if ',' not in string and ' ' not in string:
89 # Most likely passed a single string that contained an operator -- e.g.
90 # '/path/to/file' or 'file_pattern*'. If a comma isn't in the string, then
91 # it can't have been a tuple, so assume it's an unquoted string.
92 # If passed strings containing a comma (user probably expects conversion
93 # to a tuple) or whitespace (user might expect implicit conversion to
94 # tuple?) raise an exception.
95 value = string
96 else:
97 msg = (
98 f'Error while parsing string: {string} as tuple. If you intended to'
99 ' pass the argument as a single element, use quotes such as `--flag'
100 f' {repr(repr(string))}, otherwise insert quotes around each element.'
101 )
102 if ' ' in string:
103 msg += (
104 ' Use commas instead of whitespace as the separator between'
105 ' elements.'
106 )
107 raise ValueError(msg) from exc
108
109 # Make sure we return a tuple.
110 if isinstance(value, tuple):
111 return value
112 elif (isinstance(value, collections.abc.Iterable) and
113 not isinstance(value, str)):
114 return tuple(value)
115 else:
116 return (value,)