Skip to content

Conversation

@cdleonard
Copy link

@cdleonard cdleonard commented Jun 16, 2025

Fixes issues #32 and #65

ArgumentDefaultsHelpFormatter is currently broke because argparse_dataclass always passes a default value of dataclasses.MISSING to argparse. This is done in order to ensure that when default_factory is used it is only called exactly once at parse time.

Relax this behavior to allow an additional call to default_factory at parser creation time so that defaults are properly visible. This can break when default_factory has side-effects but that would be a very bad practice.

It is still guaranteed that default_factory() is called for each new parse so something like default_factory=dt.datetime.now works exactly as expected.

This is implemented by initializing an argparse.Namespace before parsing which fills in all fields which have dataclass-level default values. This prevents argparse from assigning the argparse-level default and ensures that default_factory is called for a fresh result each parse.

Still check that default_factory takes effect called at parsing time,
but allow additional calls to default_factory in order to initialize
argparse option default

This breaks if default_factory has side-effects but that is an extremely
bad idea. It's much more useful to support ArgumentDefaultsHelpFormatter
instead.
…elds with dataclass-level defaults

This prevents argparse from assigning the argparse-level default. This
ensures that any default_factory is always called at parsing time
instead of parser-creation time.
This is an explicit test for the expected behavior in issue mivade#32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant