ae.literal

literal type detection and evaluation

a number, calendar date or other none-text-value gets represented by a literal string, if entered as user input or has to be stored, e.g. as configuration variable.

the Literal class implemented by this portion converts such a evaluable literal string into the corresponding value (and type).

Functions

evaluable_literal(literal)

check evaluable format of literal string, possibly return appropriate evaluation function and stripped literal.

Classes

Literal([literal_or_value, value_type, name])

convert literal string into the corresponding value (and type).

evaluable_literal(literal)[source]

check evaluable format of literal string, possibly return appropriate evaluation function and stripped literal.

Parameters

literal (str) – string to be checked if it is in the evaluable literal format and if it has to be stripped.

Return type

Tuple[Optional[Callable], Optional[str]]

Returns

tuple of evaluation/execution function and the (optionally stripped) literal string (removed triple high-commas on expression/code-blocks) - if literal is in one of the supported evaluable literal formats - else the tuple (None, <empty string>).

class Literal(literal_or_value=None, value_type=None, name='LiT')[source]

Bases: object

convert literal string into the corresponding value (and type).

pass the literal string on instantiation as first (the literal_or_value) argument. the second argument specifies the expected value type:

>>>number = Literal("3", int)

alternatively assign the evaluable literal string after the instantiation, directly to the value attribute of the Literal instance:

>>>number = Literal(value_type=int)
>>>number.value = "3"

the corresponding int value provides the value attribute:

>>>assert number.value == 3
>>>assert type(number.value) is int

the second argument Literal.value_type is not needed when the literal string indicates the exact type:

>>>number = Literal("6")
>>>assert type(number.value) is int

specifying the second argument forces/restricts the value to a type, e.g. in the following example to a float even if the literal specifies an integer:

>>>float_number = Literal("9", float)
>>>assert float_number.value = 9.0
>>>assert type(float_number.value) is float

any type can be specified as the literal value type:

my_list = Literal(value_type=list)
my_dict = Literal(value_type=dict)
my_datetime = Literal(value_type=datetime.datetime)
my_instance = Literal(value_type=MyClass)

by converting an evaluable python expression literal the value type get automatically determined. for example the following literal gets automatically converted into a datetime object:

>>>datetime_value = Literal('(datetime.datetime.now())')

also if assigned directly to the value attribute:

>>>date_value = Literal()
>>>date_value.value = '(datetime.date.today())'

Hint

the literal string of the last two examples has to start and end with round brackets, to mark it as a evaluable literal.

to convert calendar date literal strings into one of the supported ISO formats (DATE_TIME_ISO or DATE_ISO), the expected value type has to be specified:

>>>date_value = Literal('2033-12-31', value_type=datetime.date)
>>>assert date_value.value == datetime.date(2033, 12, 31)

a ValueError exception will be raised if the conversion fails, or if the result cannot be converted into the requested value type:

>>>date_literal = Literal(value_type=datetime.date)
>>>date_literal.value = "invalid-date-literal"
>>>date_value = date_literal.value             # value getter raises ValueError

all supported literal formats are documented at the value property/attribute.

__init__(literal_or_value=None, value_type=None, name='LiT')[source]

create new Literal instance.

Parameters
  • literal_or_value (Optional[Any]) – initial literal (evaluable string expression) or value of this instance.

  • value_type (Optional[Type]) – type of the value of this instance (def=determined latest by/in the value property getter).

  • name (str) – name of the literal (only used for debugging/error-message).

__repr__()[source]

Return repr(self).

property value: Any

property representing the value of this Literal instance.

Setter

assign literal or a new value; can be either a value literal string or directly the represented/resulting value. if the assigned value is not a string and the value type of this instance got still unspecified then this instance will be restricted to the type of the assigned value. assigning a None value will be ignored - neither the literal nor the value will change with that!

Getter

return the literal value; on the first call the literal will be evaluated (lazy/late) and the value type will be set if still unspecified. further getter calls will directly return the already converted literal value.

if the literal of this Literal instance coincide with one of the following evaluable formats then the value and the type of the value gets automatically recognized. an evaluable formatted literal strings has to start and end with one of the character pairs shown in the following table:

starts with

ends with

evaluation value type

(

)

tuple literal or expression

[

]

list literal

{

}

dict literal

string literal

string literal

‘’’

‘’’

code block with return

“””

“””

code block with return

other supported literals and values

literals with type restriction to a boolean type are evaluated as python expression. this way literal strings like ‘True’, ‘False’, ‘0’ and ‘1’ will be correctly recognized and converted into a boolean value.

literal strings that representing a date value (with type restriction to either datetime.datetime or datetime.date) will be converted with the parse_date() function and should be formatted in one of the standard date formats (defined via the ae.base constants DATE_TIME_ISO and DATE_ISO).

literals and values that are not in one of the above formats will finally be passed to the constructor of the restricted type class to try to convert them into their representing value.

Return type

Any

append_value(item_value)[source]

add new item to the list value of this Literal instance (lazy/late self.value getter call function pointer).

Parameters

item_value (Any) – value of the item to be appended to the value of this Literal instance.

Return type

Any

Returns

the value (==list) of this Literal instance.

this method gets e.g. used by the ConsoleApp method add_option() to have a function pointer to this literal value with lazy/late execution of the value getter (value.append cannot be used in this case because the list could have be changed before it get finally read/used).

Note

this method calls the append method of the value object and will therefore only work if the value is of type list (or a compatible type).

convert_value(lit_or_val)[source]

set/change the literal/value of this Literal instance and return the represented value.

Parameters

lit_or_val (Any) – the new value to be set.

Return type

Any

Returns

the final/converted value of this Literal instance.

this method gets e.g. used by the ConsoleApp method add_option() to have a function pointer to let the ArgumentParser convert a configuration option literal into the represented value.

type_mismatching_with(value)[source]

check if this literal instance would reject the passed value because of type mismatch.

Parameters

value (Any) – new literal value.

Return type

bool

Returns

True if the passed value would have an type mismatch or if literal type is still not set, else False.

_determine_value(lit_or_val)[source]

check passed value if it is still a literal determine the represented value.

Parameters

lit_or_val (Any) – new literal value or the representing literal string.

Return type

Any

Returns

determined/converted value or self._lit_or_val if value could not be recognized/converted.

_chk_val_reset_else_set_type(value)[source]

reset and return passed value if is None, else determine value type and set type (if not already set).

Parameters

value (Any) – just converted new literal value to be checked and if ok used to set an unset type.

Return type

Any

Returns

passed value or the stored literal/value if passed value is None.