Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Python "os.environ.get" ever return a non-string?

In this code here, they use os.environ to get the value of an environment variable, and then immediately check to see if it is an instance of their custom classes.

value = os.environ.get(variable)
...
elif isinstance(value, ConfigList) or isinstance(value, ConfigTree):

Is it actually possible that the value will be an instance of their custom classes? Is this dead code?

like image 579
movermeyer Avatar asked Oct 09 '16 23:10

movermeyer


1 Answers

Anything that comes from the outside will be just a string, I guess.

On the other hand if you are adding something to the environment from the Python code, then you have just a bit more freedom.

Adding anything but a string still fails:

>>> os.environ['a'] = 89
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python27\lib\os.py", line 420, in __setitem__
    putenv(key, item)
TypeError: must be string, not int

However, you could make your own class inherited from str:

class C(str):
    pass

os.environ['a'] = C()

In Python2 this seems to do the trick:

>>> type(os.environ['a'])
<class '__main__.C'>

However, in Python 3 it does not. It looks like it just saves a string:

>>> type(os.environ['a'])
<class 'str'>

Still, that does not explain the code from pyhocon. I don't see how that object could be pushed into os.environ.

Unless they monkeypatched os.environ... In that case, anything would be possible.

like image 107
zvone Avatar answered Sep 28 '22 09:09

zvone