pyscript icon indicating copy to clipboard operation
pyscript copied to clipboard

NameError: name 'now' is not defined

Open shashchatter opened this issue 7 months ago • 10 comments

This is a new error, got on first HA restart after updating pyScript to 2.0.0 and HA to 2026.4.4.

2026-05-05 16:00:00.012 ERROR (MainThread) [custom_components.pyscript.function] run_coro: got exception Traceback (most recent call last): File "/config/custom_components/pyscript/eval.py", line 936, in aeval raise NameError(f"name '{val.name}' is not defined") NameError: name 'now' is not defined

PyScript: 2.0.0

Installation method Home Assistant Container Core 2026.4.4 Frontend 20260325.8

shashchatter avatar May 05 '26 16:05 shashchatter

It's not clear yet what the issue is. Please enable debug logging for Pyscript and restart Home Assistant. Add custom_components.pyscript: debug to the logger.logs section in configuration.yaml:

logger:
  default: info
  logs:
    custom_components.pyscript: debug

dmamelin avatar May 05 '26 17:05 dmamelin

Can you also include the pyscript user code is being executed, ideally localized to where the error occurs? Prior versions of pyscript silently ignored certain errors. It's quite possible there is a latent error in your user code that is now being reported.

craigbarratt avatar May 05 '26 17:05 craigbarratt

It's not clear yet what the issue is. Please enable debug logging for Pyscript and restart Home Assistant. Add custom_components.pyscript: debug to the logger.logs section in configuration.yaml:

logger: default: info logs: custom_components.pyscript: debug

I was unable to reproduce this with the logger set to debug, and then back to info. I will be on the lookout to see if this happens again.

shashchatter avatar May 05 '26 18:05 shashchatter

Can you also include the pyscript user code is being executed, ideally localized to where the error occurs? Prior versions of pyscript silently ignored certain errors. It's quite possible there is a latent error in your user code that is now being reported.

You are right, of course it could be latent in user code. I haven't been able to reproduce the issue yet. Will keep watching. I wasn't running or invoking a script manually through a button or call from Settings->Developer tools. It must be from code ececuted from one of the triggers, not sure yet about which one.

shashchatter avatar May 05 '26 18:05 shashchatter

Lucked out, saw the error, with a second error with the function name, both errors turned out to be in the same function:

2026-05-06 20:00:00.023 ERROR (MainThread) [custom_components.pyscript.function] run_coro: got exception Traceback (most recent call last):
  File "/config/custom_components/pyscript/eval.py", line 936, in aeval
    raise NameError(f"name '{val.name}' is not defined")
NameError: name 'now' is not defined

2026-05-06 20:00:00.108 ERROR (MainThread) [custom_components.pyscript.function] run_coro: got exception Traceback (most recent call last):
  File "/config/custom_components/pyscript/eval.py", line 929, in ast_not_implemented
    raise NotImplementedError(f"{self.name}: not implemented ast " + name)
NotImplementedError: scripts.solar.solar_optimizer_monitor.evening_production_summary: not implemented ast ast_generatorexp

Fixed "now()" to use datetime.datetime.now(). The second was to change from generator to list exprssion.

shashchatter avatar May 06 '26 20:05 shashchatter

It would be helpful to add self.name for the NameError exception in: File "/config/custom_components/pyscript/eval.py", line 936, in aeval

shashchatter avatar May 06 '26 20:05 shashchatter

Could you provide the full code of scripts.solar.solar_optimizer_monitor.evening_production_summary?

ast_generatorexp has never been supported in Pyscript: #564

It would be helpful to add self.name for the NameError exception in:

Fixed in #837 - please wait for the release.

dmamelin avatar May 06 '26 22:05 dmamelin

This is after I changed the generator expression to list expression (rem oved other functions in file):

from pyscript_mock import *
import chl.notification.notify_helper as notify_helper
import datetime

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
NUM_PANELS         = 31
PANEL_PREFIX       = "sensor.power_4817791_1_0_"   # + panel number (1-31)
DAILY_PREFIX       = "sensor.panel_1_0_"             # + panel number + "_daily_production"
FLEET_AVG_MIN_W    = 30     # fleet avg must exceed this before deviance checks run
UNDERPERFORM_RATIO = 0.60   # flag panel if power < fleet_avg × this ratio
DEAD_THRESHOLD_W   = 5      # below this while fleet is active = panel may be dead
CHECK_INTERVAL_MIN = 30     # deviance check period (minutes); matched to cron below
HOURS_PROD_START   = 7      # local hour — production season starts
HOURS_PROD_END     = 21     # local hour — production season ends

# Tracks panels already alerted today: {panel_num: "underperform"|"dead"}
_alerted_today: dict[int, str] = {}


# ---------------------------------------------------------------------------
# Evening production summary — posted at sunset-ish (20:00)
# ---------------------------------------------------------------------------
@time_trigger("cron(0 20 * * *)")
async def evening_production_summary(**kwargs):
    """
    Post a summary of today's per-panel production to the persistent notification.
    Lists today's totals for every panel and flags outliers.
    """
    powers = _panel_powers()
    avg = _fleet_avg(powers)

    daily_vals = {}
    for n in range(1, NUM_PANELS + 1):
        val = state.get(f"{DAILY_PREFIX}{n}_daily_production")
        try:
            daily_vals[n] = float(val or 0)
        except (TypeError, ValueError):
            daily_vals[n] = 0.0

    total_kwh = sum(daily_vals.values())
    best_n    = max(daily_vals, key=daily_vals.get)
    worst_n   = min([n for n, v in daily_vals.items() if v > 0], key=daily_vals.get, default=None) if [v for v in daily_vals.values() if v > 0] else None
    fleet_avg_daily = total_kwh / NUM_PANELS if NUM_PANELS else 0

    lines = [f"Total today: {total_kwh:.2f} kWh across {NUM_PANELS} panels."]
    lines.append(f"Best panel: 1.0.{best_n} → {daily_vals[best_n]:.3f} kWh")
    if worst_n:
        lines.append(f"Lowest panel: 1.0.{worst_n} → {daily_vals[worst_n]:.3f} kWh")
    lines.append(f"Fleet avg per panel: {fleet_avg_daily:.3f} kWh")

    low_panels = [
        f"1.0.{n} ({v:.3f} kWh)"
        for n, v in daily_vals.items()
        if v > 0 and v < fleet_avg_daily * 0.65
    ]
    if low_panels:
        lines.append(f"⚠ Below 65% of average today: {', '.join(low_panels)}")

    service.call(
        "persistent_notification", "create",
        notification_id="solar_daily_summary",
        title=f"Solar Daily Summary — {total_kwh:.2f} kWh",
        message="\n".join(lines),
    )
    log.info("Solar optimizer monitor: evening summary posted (%.2f kWh total).", total_kwh)

shashchatter avatar May 06 '26 22:05 shashchatter

Version 2.0.1 has been released with detailed tracebacks.

The issue with now is, I think, a bug in user code, but before the 2.0.0 release it was hidden from the user. ast_generatorexp is not supported in Pyscript (yet?).

dmamelin avatar May 07 '26 11:05 dmamelin

Thanks @shashchatter. To sum up where this ended up:

  • The NameError: name 'now' is not defined came from now() in the script. now is not a built-in pyscript function outside a time trigger, so that error is correct, and the message now names the missing variable (https://github.com/custom-components/pyscript/pull/837).

  • The not implemented ast ast_generatorexp error is fixed by https://github.com/custom-components/pyscript/pull/917, which adds support for generator expressions. I checked on current master that sum(x for x in range(4)) inside a function returns 6.

So you can switch back from the list expression if you like. I think this can be closed.

HoneyBearTech avatar Nov 22 '26 00:11 HoneyBearTech