2

I would like a user defined a series of strings

user_input = ('cat', 'cactus', 'cat')

which correspond to a series of objects to be instantiated from a dictionary of possible objects

classes = {
    'cat': Cat,
    'cactus': Cactus,
 }

Where the Cat and Cactus correspond to classes which descend from a parent class

class Pet():
    ...

class Cat(Pet):
    def __init__(self, name, colour):
        Pet.__init__(self, name, colour)
        ...

class Cactus(Pet):
    def __init__(self, name, colour):
        Pet.__init__(self, name, colour)
        ...

I try to add object type to a list

pet_types = []
for i in range(0,3):
    try:
        pet_type.append(classes[user_input[i]])
    except:
        raise Exception('type no exist')

But when I do this the exception is raised telling me "type no exist" when the string corresponds exactly to the dictionary entry! Why is this happening?

I then want to use pet_types like this

pet_500 = pet_types[500](name,colour)
3
  • 1
    Start by not using a blanket try...except. What is the actual exception being raised? Commented Oct 8, 2017 at 20:45
  • 1
    Side note: don't loop over range() when you could just loop ever user_input directly. Commented Oct 8, 2017 at 20:47
  • I think you're looking for a factory pattern. en.wikipedia.org/wiki/Factory_method_pattern Commented Oct 8, 2017 at 20:48

1 Answer 1

3

Catching any exception (except:) is a dodgy practice, as is hiding the original exception with your own, without even logging it.

The combination of these two dodgy practices in this case hid the fact that you have a typo, and you're trying to access the undefined pet_type (singular), instead of the variable you actually have - pet_types (plural). Fix it and you should be fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes you're correct, that is a bit embarrassing! It works fine and without the exception being thrown. In future I won't add the custom exception!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.