ソースを参照

added new utils module: enumerations. Refactored utils: created according submodules

Dimitri Korsch 6 年 前
コミット
ddb68a28c4

+ 0 - 8
cvargparse/utils.py

@@ -1,8 +0,0 @@
-def factory(func):
-	"""
-		Returns 'self' at the end
-	"""
-	def inner(self, *args, **kw):
-		func(self, *args, **kw)
-		return self
-	return inner

+ 2 - 0
cvargparse/utils/__init__.py

@@ -0,0 +1,2 @@
+from .decorators import *
+from .enumerations import *

+ 10 - 0
cvargparse/utils/decorators.py

@@ -0,0 +1,10 @@
+
+def factory(func):
+	"""
+		Factory decorator. Executes the decorated
+		method/function and returns 'self' at the end.
+	"""
+	def inner(self, *args, **kw):
+		func(self, *args, **kw)
+		return self
+	return inner

+ 37 - 0
cvargparse/utils/enumerations.py

@@ -0,0 +1,37 @@
+from enum import Enum, EnumMeta
+
+
+class MetaBaseType(EnumMeta):
+	"""
+		MetaType for the base enumeration type.
+	"""
+
+	def __contains__(cls, item):
+		"""
+			Redefines the "in" operation.
+		"""
+		if isinstance(item, str):
+			return item.lower() in cls.as_choices()
+		else:
+			return super(MetaBaseType, cls).__contains__(item)
+
+class BaseType(Enum, metaclass=MetaBaseType):
+	"""
+		Enum base type. Can be used to define argument choices.
+		It also enables to quickly creat, get and display the defined choices.
+	"""
+
+	@classmethod
+	def as_choices(cls):
+		return {e.name.lower(): e for e in cls}
+
+	@classmethod
+	def get(cls, key):
+		key = key.lower()
+		choices = cls.as_choices()
+		if key in choices:
+			return choices.get(key)
+		elif cls.Default:
+			return cls.Default
+		else:
+			raise KeyError('Unknown key and no default')