Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can os.environ['PYTHONHASHSEED'] be set dynamically from within an application?

Tags:

python

Can it be changed for the current process by simply setting it to a new value like this?

os.environ['PYTHONHASHSEED'] = 'random'
like image 589
Bob Avatar asked Sep 05 '14 10:09

Bob


1 Answers

It depends by what you mean.

If you mean to change the behaviour of the current interpreter than the answer is no:

  1. Modifying os.environ isn't reliable, since in some OSes you cannot modify the environment (see the documentation for os.environ).

  2. Environmental variables are checked only when launching the interpreter, so changing them afterwards will not have any effects for the current python instance. From the documentation:

    These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I.

    (which implies they are only checked when launching the interpreter, well before any user-code is run).

AFAIK, the random hash seed cannot be set dynamically, so you have to restart the interpreter if you want to activate hash randomization.

If you mean to make new processes spawned by the current interpreter behave as if that value was set before, then yes, assuming that you are running on a platform that supports putenv. When spawning a new process, by default, it inherits the environment of the current process. You can test this using a simple script:

#check_environ.py
import os
import subprocess

os.environ['A'] = '1'
proc = subprocess.call(['python', '-c', 'import os;print(os.environ["A"])'])

Which yields:

$ python check_environ.py
1

Note that there exist known bugs in putenv implementations (e.g. in Mac OS X), where it leaks memory. So modifying the environment is something you want to avoid as much as possible.

like image 79
Bakuriu Avatar answered Oct 16 '22 09:10

Bakuriu