InputElement¶
Bases: ABC
An element is an object that will be interpreted based on the Project's mode (script
execution, extraction, streamlit code generation, etc.). OneCode projects should not
directly call the InputElement but its corresponding static function defined as the snake
case of the element class name. For instance:
Failure
# wrong
x = MyInputElement(key, value, label)
Success
# correct
x = my_input_element(key, value, label)
InputElement is the base class for input type parameter. By inheriting it, it is mandatory
to define:
_value_type: internal attribute to ensure the type of the value is correct at runtime._validate(): internal method to ensure the value checks out at runtime.streamlit(): method returning the Streamlit code to be generated.
Note
Depending on your case, you may need to subclass value too (e.g. like CsvReader
and FileInput).
Tip
Don't forget that the Python filename of an element should correspond to the snake case
form of the element class name (e.g. FileInput -> file_input.py). You may use
pydash functions snake_case() and pascal_case() to find the right conversion
between the two forms.
Attributes:
| Name | Type | Description |
|---|---|---|
label |
str
|
Human readable name typically used by |
value |
Optional[Any]
|
Actual value of the element. |
disabled |
str
|
The string condition typically used by |
_value_type: type
abstractmethod
property
¶
You must re-implement this function to return the expected type for the value.
This _value_type is used to check to the proper type at runtime.
Returns:
| Type | Description |
|---|---|
type
|
The type of the value (built-in type or typing). |
Example
@property
def _value_type(self) -> type:
return Union[str, bool]
disabled: str
property
¶
Get the whether the element is disabled as a string. It is primarly meant to be
directly used in the Streamlit generated code for the disabled parameter.
See streamlit() for more information.
Returns:
| Type | Description |
|---|---|
str
|
The conditional string to be used in |
kind: str
property
¶
Returns:
| Type | Description |
|---|---|
str
|
The element class name. |
label: str
property
¶
Get the label with triple-quotes and escaped to handle human-readable string.
It is primarly meant to be directly used in the Streamlit generated code for the
label parameter.
See streamlit() for more information.
Returns:
| Type | Description |
|---|---|
str
|
The string to be used in |
Example
from onecode import Mode, Project, slider
Project().mode = Mode.CONSOLE
x = slider("Hello l'aspirateur!", None, optional=True)
assert x.label == "'''Hello l\'aspirateur!'''"
value: Optional[Any]
property
¶
Get the value of the element. By default this value is the one provided during at the initialization. Feel free to overwrite this property as required. For instance, FileInput and CsvReader re-implement it for their own purpose.
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
By default, the same as the initial value. |
__call__()
¶
Internal cornerstone for OneCode to distribute the action to perform according to the Project mode.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the Project mode is unknown, e.g. if there is no method matching the mode name. |
__init__(key, value, label=None, count=None, optional=False, hide_when_disabled=False, kwargs)
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
ID of the element. It must be unique as it is the key used to story data in
Project(), otherwise it will lead to conflicts at runtime in both execution and
Streamlit modes. The key will be transformed into snake case and slugified to avoid
any special character or whitespace. Note that an ID cannot start with |
required |
value |
Optional[Any]
|
Initial value for the parameter. This value may be transformed depending on the element. |
required |
label |
Optional[str]
|
Typically to be used by Streamlit for display purpose only. If not defined, it
will default to the |
None
|
count |
Optional[Union[int, str]]
|
Specify the number of occurence of the widget. OneCode typically uses it for the
streamlit case. Note that if |
None
|
optional |
Union[bool, str]
|
Specify whether the value may be None. |
False
|
hide_when_disabled |
bool
|
Only used by Streamlit: if element is optional, set it to True to hide it from the interface, otherwise it will be shown disabled. |
False
|
**kwargs |
Any
|
Extra arguments to populate the element with. Argument names cannot overwrite
existing attributes or methods name such as |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if the |
AttributeError
|
if one the |
_build_streamlit()
¶
Function called when Project mode is Mode.STREAMLIT. The Streamlit block code will be
prepared using the element parameters (such as count, optional, hide_when_disabled,
etc.) as well as the block code returned by the
streamlit() function. This function makes it easy to
extend the InputElement without worrying about the count, optional and
hide_when_disabled attributes.
Returns:
| Type | Description |
|---|---|
str
|
The full block code generated by this |
str
|
Streamlit app code. |
_console()
¶
Function called when Project mode is Mode.CONSOLE.
Returns:
| Type | Description |
|---|---|
InputElement
|
This |
_execute()
¶
Function called when Project mode is Mode.EXECUTE. The value will first be collected,
prepared, validated then added to the Project().data before being returned.
Returns:
| Type | Description |
|---|---|
Any
|
The value of this element after resolution (collection, preparation and validation). |
_extract()
¶
Function called when Project mode is Mode.EXTRACT. The value will be collected and added
to the Project().data before returning it as key-value object.
Returns:
| Type | Description |
|---|---|
Tuple[str, Any]
|
The pair |
_extract_all()
¶
Function called when Project mode is Mode.EXTRACT_ALL. The value will be collected and
added to the Project().data before returning it as key-value object along with all
other element parameters, such as key, kind, label, etc.
Returns:
| Type | Description |
|---|---|
Tuple[str, Any]
|
The full parameter set constituting this element as a dictionnary. |
_load_then_execute()
¶
Function called when Project mode is Mode.LOAD_THEN_EXECUTE. The value will first be
collected, prepared, validated then added to the Project().data before being returned.
Returns:
| Type | Description |
|---|---|
Any
|
The value of this element after resolution (collection, preparation and validation). |
_prepare_and_validate(value)
¶
Internal function used in Mode.EXECUTE and Mode.LOAD_THEN_EXECUTE to prepare the value,
check is type, then validate it before returning it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value |
Optional[Any]
|
Value to be prepared and validated. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the value is None but is not optional or the value is of incorrect type. |
_validate(value)
abstractmethod
¶
You must re-implement this function to validate at runtime the value before being returned during the OneCode project execution. This function must raise an error in case the value is incorrect/inconsistent wrt the element parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value |
Any
|
Prepared value to be checked (do not use |
required |
Example
For instance, a slider value will fail to validate if it is outside its range:
def _validate(
self,
value: Union[float, int]
) -> None:
if self.min > self.max:
raise ValueError(
f'''[{self.key}] Minimum cannot be greater than maximum:
{self.min} > {self.max}'''
)
elif value < self.min:
raise ValueError(
f'''[{self.key}] Value lower than minimum:
{value} < {self.min}'''
)
elif value > self.max:
raise ValueError(
f'[{self.key}] Value greater than maximum: {value} > {self.max}'
)
imports()
staticmethod
¶
Re-implement this function in case your Streamlit code requires specific Python package import. This function should return a list of import statement as string.
Note that the following packages are already imported (not needed to return them in that
list): os, json, uuid, pydash, streamlit as st.
Example
@staticmethod
def imports() -> List[str]:
return [
"import numpy as np",
"import plotly"
]
init()
staticmethod
¶
Re-implement this function in case your Streamlit code requires specific initialization
statements. Note that all variables starting with a _ are reserved.
Example
@staticmethod
def init() -> str:
return '''
def x(angle):
return np.deg2rad(angle%360)
'''
streamlit(id)
abstractmethod
¶
You must re-implement this function to return the expected Streamlit block code for this element. This block code will be written out to the generated Streamlit App code.
Typical attributes that will be useful:
- label: can be directly piped to the Streamlit widget label parameter. This attribute
has been automatically setup for you to use and will properly escape the potential
troublesome characters.
-
disabled: can be directly piped to the Streamlitdisabledwidget parameters. This attribute has been automatically setup for you to use and will properly take theoptionalargument into account regardless ofoptionalbeing an expression, a boolean or None. Therefore, do not useoptionalorhide_when_disabled, usedisableddirectly. -
key: it must be used as the variable name for the Streamlit widget. -
all other attributes that are specific to your widget, e.g.
min,max,stepfor a Slider, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id |
str
|
Must be used as the |
required |
Returns:
| Type | Description |
|---|---|
str
|
The Streamlit block code to be output in the generated Streamlit App code. |
Example
def streamlit(
self,
id: str
) -> str:
return f'''
# Slider
{self.key} = st.slider(
{self.label},
min_value={self.min},
max_value={self.max},
value={self.value},
step={self.step},
disabled={self.disabled},
key={id}
)
'''
Tip
Remember: no need to use optional, hide_when_disabled and count, they are
already automatically taken into account to make your life easier. Use disabled,
label, key and id