Is it safe to encrypt the private key, store it in a variable and decrypt when required?
Or this approach is vulnerable?

Is it safe to encrypt the private key, store it in a variable and decrypt when required?
Or this approach is vulnerable?

What is the goal? It doesn't make the code safer. The AES key it is encrypted under is sitting in memory exposed. And the original private key wasn't zeroed anyways.
Best practice is to read a passphrase from the user, decrypt an encrypted key, and hold in memory... but zero the passphrase right after using it, and zero the decrypted key before the program exits. If the program crashes, oops, it could leak. But the program must have the key, so that is the best that you can do without e.g. a hardware device or a remote signer of some kind.
Goal is to write a python script that could sign a bitcoin transaction itself and private key isn't leaked.
- User runs this script on machine, gets a new address, sends some bitcoin and a new address, script sends bitcoin back to user's address
- User doesn't know private key that was used by script to sign the transaction
The moment unencrypted private key touches the memory - forget about safety. Even C and rust compilers create copies all around (and zeroize doesn’t help), what to say about python, go and other garbage-collector based languages…