Skip to content
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

make _add_dataclass_options public #58

Open
martinResearch opened this issue Aug 21, 2023 · 3 comments · May be fixed by #59
Open

make _add_dataclass_options public #58

martinResearch opened this issue Aug 21, 2023 · 3 comments · May be fixed by #59
Labels
enhancement New feature or request good first issue Good for newcomers

Comments

@martinResearch
Copy link

Hi,

I would like to be able to use _add_dataclass_options directly in some of my code in order to be able to continue using normal argparse.ArgumentParser instances and use a dataclass to define only a subset of my script arguments.
Would it be possible to expose _add_dataclass_options as a public function i.e. remove the initial underscore?

@mivade
Copy link
Owner

mivade commented Sep 1, 2023

I don't see why not. Feel free to make a pull request!

@jcal-15
Copy link
Contributor

jcal-15 commented Dec 10, 2024

I think making _add_dataclass_options public is not the correct thing to do.

It is only one step in the process of initializing the dataclass. It configures the ArgumentParser assuming that the output will be passed into the dataclass for the final stage of initialization. This currently only means that the default values don't get set to the expected values after calling parse_args but later updates might bring other behaviors that don't make sense when it is public function.

@jcal-15
Copy link
Contributor

jcal-15 commented Dec 17, 2024

in some of my code in order to be able to continue using normal argparse.ArgumentParser instances and use a dataclass to define only a subset of my script arguments.

I might not be fully understanding your use case but it seems like parse_known_args might work for what you are doing.

Example

import argparse

from dataclasses import dataclass
from argparse_dataclass import parse_known_args

@dataclass
class DataclassArgs:
    name: str
    clear: bool


def main():
    dc_args, remaining = parse_known_args(DataclassArgs)

    parser = argparse.ArgumentParser()
    parser.add_argument("--foo", action="store_true")
    args = parser.parse_args(remaining)

    print(dc_args)
    print(args)

if __name__ == "__main__":
    main()

usage

$ python ex_argparse_dataclass.py --name "Fred" --foo
DataclassArgs(name='Fred', clear=False)
Namespace(foo=True)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers
Projects
None yet
3 participants