Is there a way to set M1 mps fallback environment variable in-code?

I want to automatically set 'PYTORCH_ENABLE_MPS_FALLBACK=1' environment variable.

I tried

import os

It didn’t work.
Is there a direct way to set it in Pytorch, e.g. torch.backends.mps.enable_fallback().

I would recommend exporting environment variables directly to your terminal as they are often set too late in the Python script and this won’t be read again.

I’m unsure what you mean. What won’t be read again?

Certain environment variables are read only during the import of a library and often users set them too late, which can cause confusion.
For this reason, I would not recommend setting any environment variables inside the Python script but to properly export them in your terminal before launching the Python process.