Can't use import in pyscript python scripting

I’m trying to create a simple function using pyscript that needs to import datetime.
I get an error after saving my script in the log:

Exception in </config/pyscript/season.py> line 2: import datetime ^ SyntaxError: invalid syntax (season.py, line 2)

This is my code:

@service(supports_response="only")
import datetime
from datetime import date

def season(return_response=True):
    now = date.today()
    m = now.month
    x = m%12 // 3 + 1
    season = x
    return season

I have run the same code in an IDLE Shell in Windows (without the @service bit) and it runs without error (and works).

I have installed pyscript as detailed in the documentation, setting the two options for import and global to true in my configuration.yaml file.
My pyscript folder is in the config path (same as configuration.yaml).

I have successfully created and run another python script (using pyscript) earlier, so I know at least it might work. However, it appears that import statements cause syntax errors, so it looks like “allow_all_imports: true” is not taking effect.

I’ve looked at other community posts but can’t find anything that addresses my issue.

Does this look like my installation is bad?

Thanks in advance.

Did you made a mistake while posting the code here? the import commands should be at the very top, before @service part

import datetime
from datetime import date
  
@service(supports_response="only")
def season(return_response=True):
    now = date.today()
    m = now.month
    x = m%12 // 3 + 1
    season = x
    return season

Thanks Serkan, but unfortunately it didn’t solve the error.
I get other errors now:

websocket_api script: Error executing script. Error for call_service at pos 1: Failed to process the returned action response data, expected a dictionary, but got <class 'int'>

[547532094288] Error handling message: Failed to process the returned action response data, expected a dictionary, but got <class 'int'> (home_assistant_error) Grandad from fe80::6060:793a:be0c:4914 (Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0)

I tested my code using “Developer tools>ACTIONS”.

The Pyscript documentation indicates that python scripts should be run as a service, so I think that is why I’m getting latest errors because the imports were run outside of the service call.

I completely removed pyscript and re-downloaded and install it again just incase there was some issue with the configuration (yaml config vs UI), but it made no difference.

It is still not clear if there is an issue with my installation or something in pyscript broke after updates to HASS.

  • Core 2025.1.4
  • Supervisor 2024.12.3
  • Operating System 14.2
  • Frontend 20250109.2

As a matter of interest did you happen to try my code out on your system? If it works on your system then I might consider a bug report to pyscript.

Thanks again.