8

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

os.environ['PYTHONHASHSEED'] = 'random'
Bob
  • 5,809
  • 5
  • 36
  • 53

1 Answers1

12

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • 2
    With `subprocess.call`, you can work around modifying the environment by passing an explicit, augmented environment. `e = dict(os.environ); e.update(PYTHONHASHSEED='random'); subprocess.call([...], env=e)` – chepner Sep 05 '14 at 13:45
  • @chepner Yes, I well known that. It's clearly mentioned in the docs. I was answering a question about *modifying* the environment *of the current process*. In fact that part of the answer is a guess at what the OP may mean; if he edits his question clarifying what he means I'll add that suggestion (this was already in my thoughts when I first wrote the answer). – Bakuriu Sep 05 '14 at 14:13