简体   繁体   中英

Confusion about environmental variables in python

I'm having a bit of trouble figuring out the use of environmental variables in a bit of sample code from one of the MIT 6.006 'Intro to algorithms' course.

I just finished problem set 3, and when looking through the solutions (found here ), the code uses this sort of syntax to change variable names:

if sys.version_info >= (3,):
    xrange = range

this makes perfect sense since in python 3, range == xrange

however, later in the solution block, they end up defining different classes to overwrite existing classes. The details aren't too important here, but essentially when they do so, they put in an 'if' statement to change one Class implementation to another. For example, they create an array-based range index "BlitRangeIndex" to overwrite "RangeIndex":

if os.environ.get('INDEX') == 'blit':
  RangeIndex = BlitRangeIndex

However, I don't understand how the variable "INDEX" was ever put into the environmental variables. There is no indication in the code that this ever happened, so I don't understand how the 'if' statement is evaluated as true.

Any insight would be great! I'm still learning a lot about the inner workings of python, and I just can't seem to figure this one out.

It just assumes that you have set environment variables before running the program. For example, in a Linux environment you would do something like this:

$ export INDEX=value 
$ export CROSS=value 
$ export TRACE=value
$ python path/to/full_circuit2.py 

However, if you prefer, you can override these vaiaveis by constants, like this:

#!/usr/bin/env python

INDEX='value'
CROSS='value' 
TRACE='value'

...

You can even pass values by command line arguments:

#!/usr/bin/env python

import sys  
# other imports... 

INDEX = sys.argv[1]
CROSS = sys.argv[2]
TRACE = sys.argv[3]

...

if INDEX == 'blit': # instead if os.environ.get('INDEX')
  RangeIndex = BlitRangeIndex

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM