Setting these environment variables inside a script might be a bit dangerous and I would also recommend to set them before importing anything CUDA related (e.g. PyTorch).
It looks as if you would like to mask the GPU dynamically inside your script.
If that’s the case, I would rather use the device variable and write device-agnostic code than rely on CUDA_VISIBLE_DEVICES.