Protect against null environment variables when using os.path.expandvars
Question: How can I protect against Python's `os.path.expandvars()` treatment of
null/unset environment variables?

From
[os.path](https://docs.python.org/2/library/os.path.html#os.path.expandvars):

> Malformed variable names and references to non-existing variables are left
> unchanged.
    
    
    >>> os.path.expandvars('$HOME/stuff')
    '/home/dennis/stuff'
    >>> os.path.expandvars('foo/$UNSET/bar')
    'foo/$UNSET/bar'
    

I could perform this step separately from other path processing
(`expanduser()`, `realpath(),` `normpath()`, etc.) instead of chaining them
all together and check to see if the result is unchanged, but that is normal
when there are no variables present - so I would also have to parse the string
to see if it has any variables. I fear that may not be robust enough.

The issue comes into play when creating a file using the result. I end up with
a file with the variable name as a literal part of the file's name. I want to
instead reject the input with an exception.


Answer: You could use `string.Template`, which uses a similar dollar-sign syntax for
interpolation of variables but will raise `KeyError` if something doesn't
exist rather than leaving it in.

    
    
    import os
    from string import Template
    print(Template('$HOME/stuff').substitute(os.environ))
    

