Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Argparse within a Class __init__

Is it possible to use Argparse from within a class and if so, how would you get the parameters to the parser? Is there a better way of going about this? Here is my code so far:

class Game:
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("num_players", help="Number of players", type=int)
        ...
        args = parser.parse_args()


if __name__ == '__main__':
    g = Game()

Also Is there a way of supplying optional arguments such as --verbose?

like image 632
Spiff Avatar asked Apr 01 '26 00:04

Spiff


1 Answers

It is highly unlikely to be the best design.

The Game class should probably not care how it was initialized, and it should probably know nothing about command line arguments. You will be better off parsing the CLI args outside, then pass the arguments to Game.__init__ or at least to a dedicated Game.from_cli_args classmethod.

import argparse

class Game:
    def __init__(self, num_players):
        print('Game got {} as num_players'.format(num_players))
        self.num_players = num_players


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("num_players", help="Number of players", type=int)
    ...
    args = parser.parse_args()

    g = Game(args.num_players)

Then executing:

$ python main.py 2
Game got 2 as num_players

If you use -- as a prefix the argument will need to be passed explicitly:

parser.add_argument("--num_players", help="Number of players", type=int)

Then

$ python main.py --num_players 2
Game got 2 as num_players
like image 188
DeepSpace Avatar answered Apr 02 '26 12:04

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!