فهرست منبع

added support for 'store_true' 'store_false' actions

Dimitri Korsch 3 سال پیش
والد
کامیت
bf751c89ef
2فایلهای تغییر یافته به همراه37 افزوده شده و 8 حذف شده
  1. 3 2
      cvargparse/__init__.py
  2. 34 6
      cvargparse/utils/dataclass.py

+ 3 - 2
cvargparse/__init__.py

@@ -33,6 +33,7 @@ if __name__ == '__main__':
 		arg2: str = "something"
 
 		arg3: Choices([1, 2, 3], int) = 1
+		is_arg4: bool = False
 
-	parser = BaseParser(Args(arg3=2))
-	print(parser.parse_args("--help".split()))
+	parser = BaseParser(Args)
+	print(parser.parse_args("--is_arg4".split()))

+ 34 - 6
cvargparse/utils/dataclass.py

@@ -63,17 +63,23 @@ class FieldWrapper:
 		self._field = field
 
 	def as_arg(self) -> Arg:
-		return Arg(
-			self.name,
-			type=self.type,
-			default=self.default,
-			choices=self.choices
-		)
+		return Arg(self.name, **self.arg_kwargs)
 
 	@property
 	def field(self):
 		return self._field
 
+	@property
+	def arg_kwargs(self):
+		if self.is_option:
+			return dict(action=self.action)
+
+		return dict(
+			type=self.type,
+			default=self.default,
+			choices=self.choices,
+		)
+
 	@property
 	def name(self):
 		return f"--{self.field.name}"
@@ -82,16 +88,38 @@ class FieldWrapper:
 	def is_choice(self):
 		return isinstance(self.field.type, Choices)
 
+	@property
+	def is_option(self):
+		return self.field.type == bool
+
+	@property
+	def action(self):
+		if not self.is_option:
+			return
+
+		actions = {
+			True:  "store_false",
+			False: "store_true"
+		}
+
+		return actions.get(self.field.default)
+
 	@property
 	def type(self):
 		if self.is_choice:
 			return self.field.type._type
 
+		if self.is_option:
+			return None
+
 		return self.field.type
 
 	@property
 	def default(self):
 
+		if self.is_option:
+			return None
+
 		if self.field.default == MISSING:
 			return self.type()