Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""Convert a simple "shorthand" Python value to a `Template`.
"""
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, abc.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
elif value is int:
return Integer()
elif isinstance(value, int):
return Integer(value)
elif isinstance(value, type) and issubclass(value, util.BASESTRING):
return String()
elif isinstance(value, util.BASESTRING):
return String(value)
elif isinstance(value, set):
# convert to list to avoid hash related problems
return Choice(list(value))
elif (SUPPORTS_ENUM and isinstance(value, type)
and issubclass(value, enum.Enum)):
return Choice(value)
elif isinstance(value, list):
return OneOf(value)
elif value is float:
return Number()
elif isinstance(value, float):
return Number(value)
elif value is None:
return Template(None)
elif value is REQUIRED:
return Template()
def __init__(self, default=REQUIRED, pattern=None, expand_vars=False):
"""Create a template with the added optional `pattern` argument,
a regular expression string that the value should match.
"""
super(String, self).__init__(default)
self.pattern = pattern
self.expand_vars = expand_vars
if pattern:
self.regex = re.compile(pattern)
def as_template(value):
"""Convert a simple "shorthand" Python value to a `Template`.
"""
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, abc.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
elif value is int:
return Integer()
elif isinstance(value, int):
return Integer(value)
elif isinstance(value, type) and issubclass(value, util.BASESTRING):
return String()
elif isinstance(value, util.BASESTRING):
return String(value)
elif isinstance(value, set):
# convert to list to avoid hash related problems
return Choice(list(value))
elif (SUPPORTS_ENUM and isinstance(value, type)
and issubclass(value, enum.Enum)):
return Choice(value)
elif isinstance(value, list):
return OneOf(value)
elif value is float:
return Number()
elif isinstance(value, float):
return Number(value)
elif value is None:
return Template(None)
def as_str_expanded(self):
"""Get the value as a (Unicode) string, with env vars
expanded by `os.path.expandvars()`.
"""
return self.get(templates.String(expand_vars=True))
def as_str(self):
"""Get the value as a (Unicode) string. Equivalent to
`get(unicode)` on Python 2 and `get(str)` on Python 3.
"""
return self.get(templates.String())