-
Notifications
You must be signed in to change notification settings - Fork 74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
perf: support for custom action in config parser #361
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
import os | ||
import sys | ||
from collections import OrderedDict | ||
from collections.abc import Callable | ||
from dataclasses import MISSING, dataclass, fields | ||
from dataclasses import field as dataclass_field | ||
from typing import Any | ||
|
@@ -33,6 +34,7 @@ def arg( | |
short: str | None = None, | ||
countable: bool = False, | ||
global_default_str: str | None = None, | ||
action: Callable = None, | ||
): | ||
return dataclass_field( | ||
default=None, | ||
|
@@ -45,10 +47,39 @@ def arg( | |
"short": short, | ||
"countable": countable, | ||
"global_default_str": global_default_str, | ||
"action": action, | ||
}, | ||
) | ||
|
||
|
||
class ParseCSV(argparse.Action): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what do we get by subclassing There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ah I see we pass it to the generated argparse parser. Pretty cool! |
||
def __call__(self, parser, namespace, values, option_string=None): | ||
values = ParseCSV.parse(values) | ||
setattr(namespace, self.dest, values) | ||
|
||
@staticmethod | ||
def parse(values: str) -> list[int]: | ||
return [int(x.strip()) for x in values.split(",")] | ||
|
||
|
||
class ParseArrayLengths(argparse.Action): | ||
def __call__(self, parser, namespace, values, option_string=None): | ||
values = ParseArrayLengths.parse(values) | ||
setattr(namespace, self.dest, values) | ||
|
||
@staticmethod | ||
def parse(values: str | None) -> dict[str, list[int]]: | ||
if not values: | ||
return {} | ||
|
||
# TODO: update syntax: name1=size1,size2; name2=size3,...; ... | ||
name_sizes_pairs = values.split(",") | ||
return { | ||
name.strip(): [int(x.strip()) for x in sizes.split(";")] | ||
for name, sizes in [x.split("=") for x in name_sizes_pairs] | ||
} | ||
|
||
|
||
# TODO: add kw_only=True when we support Python>=3.10 | ||
@dataclass(frozen=True) | ||
class Config: | ||
|
@@ -152,12 +183,14 @@ class Config: | |
help="set the length of dynamic-sized arrays including bytes and string (default: loop unrolling bound)", | ||
global_default=None, | ||
metavar="NAME1=LENGTH1,NAME2=LENGTH2,...", | ||
action=ParseArrayLengths, | ||
) | ||
|
||
default_bytes_lengths: str = arg( | ||
help="set the default length candidates for bytes and string not specified in --array-lengths", | ||
global_default="0,32,1024,65", # 65 is ECDSA signature size | ||
metavar="LENGTH1,LENGTH2,...", | ||
action=ParseCSV, | ||
) | ||
|
||
storage_layout: str = arg( | ||
|
@@ -528,7 +561,12 @@ def _create_default_config() -> "Config": | |
if default == MISSING: | ||
continue | ||
|
||
values[field.name] = default() if callable(default) else default | ||
# retrieve the default value | ||
raw_value = default() if callable(default) else default | ||
|
||
# parse the default value, if a custom parser is provided | ||
action = field.metadata.get("action", None) | ||
values[field.name] = action.parse(raw_value) if action else raw_value | ||
|
||
return Config(_parent=None, _source="default", **values) | ||
|
||
|
@@ -583,6 +621,8 @@ def _create_arg_parser() -> argparse.ArgumentParser: | |
} | ||
if choices := field_info.metadata.get("choices", None): | ||
kwargs["choices"] = choices | ||
if action := field_info.metadata.get("action", None): | ||
kwargs["action"] = action | ||
group.add_argument(*names, **kwargs) | ||
|
||
return parser | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
would it be better to use a different name, e.g.,
custom_action
, to avoid potential name clashes? it might be fine as the namechoices
is also used here, but let me know if you have any concerns.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not sure I follow, name clash with what?
I'm ok with
custom_action
, but don't love the "action" nomenclature. If this is about parsing, what aboutparser
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
parser
is even more overloaded, ignore that. Eitheraction
orcustom_action
works IMO, I wouldn't worry about name clashes at that level (I thought this was a concern about shadowing)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
okay, i will stick with
action
.