OutputElement¶
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 OutputElement
but its corresponding static function defined as the snake
case of the element class name. For instance:
Failure
# wrong
x = MyOutputElement(key, value, label)
Success
# correct
x = my_output_element(key, value, label)
OutputElement
is the base class for outputs. By inheriting it, it is mandatory to define:
_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 CsvOutput
and FileOutput).
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. FileOutput
-> file_output.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 |
Any
|
Actual value of the element. |
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, text_output
Project().mode = Mode.CONSOLE
x = text_output("Hello l'aspirateur!", None)
assert x.label == "'''Hello l\'aspirateur!'''"
value: 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, FileOutput and CsvOutput re-implement it for their own purpose.
Returns:
Type | Description |
---|---|
Any
|
By default, the same as the initial value. |
__call__()
¶
Directly returns static_call().
__init__(key, value, label=None, 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 |
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
|
**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()
classmethod
¶
Function called when Project mode is Mode.STREAMLIT
. This will generate the output static
function called when the corresponding output file is selected in the Streamlit App file
tree. The function signature is made of the internal attributes and any other custom
attributes.
Note
See streamlit()
for more information.
Returns:
Type | Description |
---|---|
str
|
The block code generated by this |
str
|
Streamlit app code. |
_console()
¶
Function called when Project mode is Mode.CONSOLE
.
Returns:
Type | Description |
---|---|
OutputElement
|
This |
_execute()
¶
Function called when Project mode is Mode.EXECUTE
. The value will first be prepared,
validated then all element attributes will be output to the manifest file
(see Project.write_output()
).
Returns:
Type | Description |
---|---|
Any
|
The value of this element after resolution (preparation and validation). |
_extract()
¶
Nothing is performed: OutputElement
attributes are not extracted as the actual output
attributes will be dumped into a manifest file.
_extract_all()
¶
Nothing is performed: OutputElement
attributes are not extracted as the actual output
attributes will be dumped into a manifest file.
_load_then_execute()
¶
Directly returns _execute().
_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, an image output value will fail to validate if the file extension is not a valid/known extension such as jpeg, png, etc.
def _validate(
self,
value: str
) -> None:
_, ext = os.path.splitext(self.value)
valid_ext = [
'.jpg',
'.jpeg',
'.png',
'.svg',
]
if ext.lower() not in valid_ext:
raise ValueError(
f'''[{self.key}] Invalid image extension:
{ext} (accepted: {', '.join(valid_ext)})'''
)
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)
'''
static_call()
staticmethod
¶
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. |
streamlit()
abstractmethod
staticmethod
¶
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.
You should write this block code as the body of a static function yielding all internal
attributes (such as key
, label
, value
and kind
) and any other custom attributes
provided in this OutputElement
initialization function's signature.
For instance:
class MyOutputElement(OutputElement):
def __init__(
self,
key: str,
value: Any,
label: Optional[str],
my_extra_1: int,
my_extra_2: str
):
# ...
function _MyOutputElement(key, label, value, kind, my_extra_1, my_extra_2)
Returns:
Type | Description |
---|---|
str
|
The Streamlit block code to be output in the generated Streamlit App code. |
Example
def streamlit() -> str:
return '''
st.write(f'{key} - {label} - {value} - {kind}: {my_extra_1} | {my_extra_2}')
'''
will write out to the Streamlit App file:
# static function called when the corresponding file is selected in the tree
function _MyOutputElement(key, label, value, kind, my_extra_1, my_extra_2)
st.write(f'{key} - {label} - {value} - {kind}: {my_extra_1} | {my_extra_2}')