Created
January 18, 2016 22:57
-
-
Save mic159/168f28ea8a18a6392e38 to your computer and use it in GitHub Desktop.
input_algorithms python import validator and normaliser
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
class Import(valid_string_spec): | |
validators = [regexed("^(?P<module>[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*):(?P<class>[a-zA-Z_][a-zA-Z_0-9]*)$")] | |
def setup(self, checked_class): | |
self.checked_class = checked_class | |
def normalise_filled(self, meta, val): | |
# Run string & regex validator | |
val = super(Import, self).normalise_filled(meta, val) | |
# Now validate it is importable | |
path = self.validators[0].regexes[0][1].match(val).groupdict() | |
try: | |
module = import_module(path['module']) | |
val = getattr(module, path['class']) | |
if not issubclass(val, self.checked_class): | |
raise BadSpecValue( | |
"Wrong class type. {} is not a {}".format( | |
val.__name__ | |
, self.checked_class.__name__ | |
), | |
meta=meta | |
) | |
return val | |
except ImportError: | |
raise BadSpecValue("Import not found", val=val, meta=meta) | |
except AttributeError: | |
raise BadSpecValue("Couldnt find class", val=val, meta=meta) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment