[Python] How to safely access Optional[float] in Indie when value_or(None) gives type error?

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing an indicator in the TakeProfit's Indie language, and I'm trying to plot a marker based on a value from a higher timeframe.

    The value is declared as Optional[float], and I want to return a fallback value if it's not set. But I'm getting a confusing error about NoneType not matching float, even though I just want to check whether the optional has a value:

    Here's a minimal version of my code:

    # indie:lang_version = 5

    from indie import indicator, plot, param, color, Optional, MainContext, TimeFrame, sec_context
    from indie.plot import marker_style, marker_position, Marker

    @sec_context
    def HTF(self):
    return 1.0

    @indicator("Marker Bug - simplified", overlay_main_pane=False)
    @param.bool("enabled", default=True)
    @param.time_frame("htf", default="1D")
    @plot.marker("m", style=marker_style.LABEL, position=marker_position.ABOVE)
    class Main(MainContext):
    def __init__(self, htf: TimeFrame) -> None:
    self._val = Optional[float](None)

    if htf != self.time_frame:
    r = self.calc_on(HTF, time_frame=htf)
    if r[0] > 0:
    self._val = Optional[float](80.0)

    def calc(self, enabled: bool, htf: TimeFrame):
    return Marker(
    self._val.value_or(20.0),
    text="HTF!" if self._val.value_or(None) is not None else None,
    color=color.GREEN
    ) if enabled else Marker(None)


    This causes the error:


    Error: 26:27 could not find function definition that matches self._val.value_or call, reason: pos arg 1 of <class 'NoneType'> type does not match with the param of type <class 'float'>
    ​

    But I thought .value_or(...) is supposed to return the wrapped value or a fallback if it's None.

    What’s the correct way to test and unwrap an Optional[float] for use in a Marker(...)?

    Should I avoid passing None to value_or?

    Continue reading...

Compartilhe esta Página