15.2.121. camcops_server.cc_modules.cc_formatter¶
camcops_server/cc_modules/cc_formatter.py
Copyright (C) 2012, University of Cambridge, Department of Psychiatry. Created by Rudolf Cardinal (rnc1001@cam.ac.uk).
This file is part of CamCOPS.
CamCOPS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
CamCOPS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with CamCOPS. If not, see <https://www.gnu.org/licenses/>.
Safe alternative to str.format() that rejects anything not in the list of allowed keys.
- class camcops_server.cc_modules.cc_formatter.SafeFormatter(allowed_keys: Sequence[str])[source]¶
Safe alternative to
str.format()
that rejects anything not in the list of allowed keys.Basic usage:
from camcops_server.cc_modules.cc_formatter import SafeFormatter f = SafeFormatter(["a", "b"]) f.format("a={a}, b={b}", a=1, b=2) # OK f.format("a={a.__class__}", a=1) # raises KeyError f.format("a={a}, b={b}, c={c}", a=1, b=2, c=3) # raises KeyError
- __init__(allowed_keys: Sequence[str]) None [source]¶
- Parameters
allowed_keys – Keys that are permitted within a brace-delimited format string.
- get_field(field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) Tuple[Any, str] [source]¶
Overrides
Formatter.get_field()
(q.v.).- Parameters
field_name – name of the field to be looked up
args – positional arguments passed to
format()
(not including the format string)kwargs – keyword arguments passed to
format()
- Returns
(obj, arg_used)
whereobj
is the object that’s been looked up, andarg_used
is the argument it came from- Return type
tuple
:raises -
KeyError
if the field_name is disallowed: