Oct-01-2017, 07:52 AM
(This post was last modified: Oct-01-2017, 08:29 AM by microphone_head.)
Can anyone out there suggest a better way of using the "type" routine?
I am trying to improve my code by identifying errors. In addition
to using the "try" command I would like to identify variable types.
The idea is to identify the object type of a parameter passed by
a calling routine. I have been using the "type" routine, but believe
there must be a better way.
I am runing Python 3 on my Raspberry Pi2.
Sorry guys and girls I made a mistake on the previous submission of the code.
Here's the revised copy of the code. Note the keyword "str" when testing the "type".
I am trying to improve my code by identifying errors. In addition
to using the "try" command I would like to identify variable types.
The idea is to identify the object type of a parameter passed by
a calling routine. I have been using the "type" routine, but believe
there must be a better way.
I am runing Python 3 on my Raspberry Pi2.
def add_option(mnu_caption, txt_colour =None): if txt_colour is None: # set the menu item to its default colour. txt_colour =(255, 255, 255) else: # verify parameter is valid if "tuple" in type(txt_colour): if len(txt_colour) !=3: # we got a problem pass print("Obj type of txt_colour =", type(txt_colour), " size =", len(txt_colour)) add_option("Run Game")
Output:Obj type of txt_colour = <class 'tuple'> size = 3
Sorry guys and girls I made a mistake on the previous submission of the code.
Here's the revised copy of the code. Note the keyword "str" when testing the "type".
def add_option(mnu_caption, txt_colour =None): if txt_colour is None: # set the menu item to its default colour. txt_colour =(255, 255, 255) else: # verify parameter is valid if "tuple" in str(type(txt_colour)): if len(txt_colour) !=3: # we got a problem pass print("Obj type of parameter txt_colour =", type(txt_colour), " size =", len(txt_colour)) txtcol =(255, 255, 255) add_option("Run Game", txtcol)
Output:Obj type of parameter txt_colour = <class 'tuple'> size = 3