Last active
March 16, 2017 11:54
-
-
Save fmartingr/7239d5b2a32f2010c22d22616d5b9048 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
class BashDict(dict): | |
variable_regex = r'(\$\{([\w\d\_]+)\})' | |
default_return = '' | |
def _parse_variables(self, value): | |
if '${' in value: | |
def replace(match): | |
variable_name = match.group(2) | |
parsed = self.get(variable_name) | |
if not parsed: | |
return self.default_return | |
return parsed | |
return re.sub(self.variable_regex, | |
replace, | |
value) | |
return value | |
def __getitem__(self, key): | |
value = super(BashDict, self).__getitem__(key) | |
return self._parse_variables(value) | |
def get(self, key): | |
value = super(BashDict, self).get(key) | |
return self._parse_variables(value) | |
d = BashDict() | |
d['KEY'] = 'foo' | |
d['VAR1'] = '${KEY}pene' | |
d['VAR2'] = '${VAR1}polla' | |
d['VAR3'] = '${VAR1}${VAR2} hahah' | |
print(d['VAR1']) | |
print(d.get('VAR1')) | |
print(d['VAR2']) | |
print(d.get('VAR2')) | |
print(d['VAR3']) | |
print(d.get('VAR3')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment