Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7834785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T13:19:23+00:00 2026-06-02T13:19:23+00:00

I need to create instances of a custom object (Bar in the example below)

  • 0

I need to create instances of a custom object (Bar in the example below) based on a given string. If I do not change the type to Bar and run the below code:

import argparse

VALID_BAR_NAMES = ['alfa', 'beta', 'gamma', 'delta']


class Bar:

    def __init__(self, name):
        if not name in VALID_BAR_NAMES:
            raise RuntimeError('Bar can not be {n}, '
                               'it must be one of {m}'.format(
                                    n=name, m=', '.join(VALID_BAR_NAMES)))
        self.name = name


if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('foo', help='Specify the foo!')

    parser.add_argument('-b', '--bar', nargs='*',
                        choices=VALID_BAR_NAMES,
                        type=str,  # SELECTED TYPE
                        help=('Specify one or many valid bar(s)'))
    parsed_arguments = parser.parse_args()

I get this rather nice output when passing the invalid argment hello to -b:

usage: Example.py [-h]
                  [-b [{alfa,beta,gamma,delta} [{alfa,beta,gamma,delta} ...]]]
                  foo
Example.py: error: argument -b/--bar: invalid choice: 'hello' (choose from 'alfa', 'beta', 'gamma', 'delta')

However, if I change type=str to type=Bar and run the example again I get this output:

Traceback (most recent call last):
  File "C:\PyTest\Example.py", line 25, in <module>
    parsed_arguments = parser.parse_args()
  File "C:\Python27\lib\argparse.py", line 1688, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "C:\Python27\lib\argparse.py", line 1720, in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
  File "C:\Python27\lib\argparse.py", line 1926, in _parse_known_args
    start_index = consume_optional(start_index)
  File "C:\Python27\lib\argparse.py", line 1866, in consume_optional
    take_action(action, args, option_string)
  File "C:\Python27\lib\argparse.py", line 1778, in take_action
    argument_values = self._get_values(action, argument_strings)
  File "C:\Python27\lib\argparse.py", line 2218, in _get_values
    value = [self._get_value(action, v) for v in arg_strings]
  File "C:\Python27\lib\argparse.py", line 2233, in _get_value
    result = type_func(arg_string)
  File "C:\PyTest\Example.py", line 12, in __init__
    n=name, m=', '.join(VALID_BAR_NAMES)))
RuntimeError: Bar can not be hello, it must be one of alfa, beta, gamma, delta

Which looks pretty bad. I understand that this is due to type conversion occuring before check against available choices is done. What would be the best way to handle this be?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T13:19:24+00:00Added an answer on June 2, 2026 at 1:19 pm

    You need to create a custom action (untested):

    class Bar: 
        ...
    
    
    class BarAction(argparse.Action):
        def __call__(self,parser,namespace,values,option_string=None):
            try:  #Catch the runtime error if it occures.
               l=[Bar(v) for v in values] #Create Bars, raise RuntimeError if bad arg passed.
            except RuntimeError as E:
               #Optional:  Print some other error here.  for example: `print E; exit(1)`  
               parser.error()
    
            setattr(namespace,self.dest,l) #add the list to the namespace
    
    ...
    parser.add_argument('-b', '--bar', nargs='*',
                        choices=VALID_BAR_NAMES,
                        action=BarAction,  # SELECTED TYPE -- The action does all the type conversion instead of the type keyword.
                        help=('Specify one or many valid bar(s)'))
    
    ...
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have custom object MyClass and I need to create 3 instances of it.
I need to create an instance of an object and the type of that
I need to create at runtime instances of a class that uses generics, like
We need to create & destroy instances of QApplication, as we want to use
I need this roadmap of a Hibernate managed object instance. First, I create an
I need create custom dialog and put JPanel into it. Is it possible?
I need create clone repository. but I do not know where can I get
For my project i need to have custom urls that should not be easy
I need to create a custom allocator for std:: objects (particularly and initially for
I’m exploring Core Data custom migration, for which I need to run a test

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.