scriptconfig.smartcast module¶
- scriptconfig.smartcast.smartcast(item, astype=None, strict=False, allow_split=False)[source]¶
Converts a string into a standard python type.
In many cases this is a simple alternative to eval. However, the syntax rules use here are more permissive and forgiving.
The astype can be specified to provide a type hint, otherwise we try to cast to the following types in this order: int, float, complex, bool, none, list, tuple.
- Parameters
item (str | object) – represents some data of another type.
astype (type | None) – if None, try infer what the best type is, if astype == ‘eval’ then try to return eval(item), Otherwise, try to cast to this type. Default to None.
strict (bool) – if True raises a TypeError if conversion fails. Default to False.
allow_split (bool) – if True will interpret strings with commas as sequences. Defaults to True.
- Returns
some item
- Return type
- Raises
TypeError – if we cannot determine the type
Example
>>> # Simple cases >>> print(repr(smartcast('?'))) >>> print(repr(smartcast('1'))) >>> print(repr(smartcast('1,2,3'))) >>> print(repr(smartcast('abc'))) >>> print(repr(smartcast('[1,2,3,4]'))) >>> print(repr(smartcast('foo.py,/etc/conf.txt,/baz/biz,blah'))) '?' 1 [1, 2, 3] 'abc' [1, 2, 3, 4] ['foo.py', '/etc/conf.txt', '/baz/biz', 'blah']
>>> # Weird cases >>> print(repr(smartcast('[1],2,abc,4'))) ['[1]', 2, 'abc', 4]
Example
>>> assert smartcast('?') == '?' >>> assert smartcast('1') == 1 >>> assert smartcast('1.0') == 1.0 >>> assert smartcast('1.2') == 1.2 >>> assert smartcast('True') is True >>> assert smartcast('false') is False >>> assert smartcast('None') is None >>> assert smartcast('1', str) == '1' >>> assert smartcast('1', eval) == 1 >>> assert smartcast('1', bool) is True >>> assert smartcast('[1,2]', eval) == [1, 2]
Example
>>> def check_typed_value(item, want, astype=None): >>> got = smartcast(item, astype) >>> assert got == want and isinstance(got, type(want)), ( >>> 'Cast {!r} to {!r}, but got {!r}'.format(item, want, got)) >>> check_typed_value('?', '?') >>> check_typed_value('1', 1) >>> check_typed_value('1.0', 1.0) >>> check_typed_value('1.2', 1.2) >>> check_typed_value('True', True) >>> check_typed_value('None', None) >>> check_typed_value('1', 1, int) >>> check_typed_value('1', True, bool) >>> check_typed_value('1', 1.0, float) >>> check_typed_value(1, 1.0, float) >>> check_typed_value(1.0, 1.0) >>> check_typed_value([1.0], (1.0,), 'tuple')