Parse/Creating Types in Python
Question: I'm trying to figure out how to create types and convert the users input
according to those types. For example:

user enters: 5

5 is of type Number 5 gets added to the list

user enters: 3.5

3.5 is of type Number 3.5 gets added to the list

user enters: :true:

:true: is of type Boolean :true: gets added to the list

I want my program to to be able to convert the number 5 to an int then put it
on the stack, 3,5 to a float then put it on the stack and know that :true: has
a value of True.

Here's what I tried so far but isn't working the way its supposed to:

    
    
        #!/util/bin/python
    import re
    import shlex
    stack = []
    
    tokens = (
      ('STRING', re.compile('"[^"]+"')),  # longest match
      ('NAME', re.compile('[a-zA-Z_]+')),
      ('SPACE', re.compile('\s+')),
      ('NUMBERD', re.compile('\d.')),
      ('NUMBERI', re.compile('\d+')),
      ('TRUE', re.compile(':true:')),
      ('FALSE', re.compile(':false:')),
      )
    
    def main ():
    
    
        while 1:
            inp = input('INPUT> ')
            push(inp,stack) #Push User Input unto stack
            printStack(stack) #Print Stack
            quit(inp,stack) #Exit program if prompted  
    
    
    
    
    def push(s,list):
        tokens = shlex.split(s, posix=False)
        for token in tokens:
            if type(s) == 'NUMBERI':
                list.append(int(token))
            elif type(s) == 'NUMBERD':
                list.append(float(token))
            else:
                list.append(token)
    
        return list
    
    def printStack(stack):
        for index in stack[::-1]:
            print (index)
    
    
    
    def quit (x, stack):
        if x == "quit":
            stack.pop()
            exit(0)
    
    
    def type(s):
        i = 0
        lexeme = []
        while i < len(s):
            match = False
            for token, regex in tokens:
                result = regex.match(s, i)
                if result:
                    return(token)
                    i = result.end()
                    match = True
                    break
            if not match:
                raise Exception('lexical error at {0}'.format(i))
    
    
    
    
    def add (x,y):
        return(x + y)
    
    def sub (x,y):
        return(x - y)
    
    def mul (x,y):
        return(x * y)
    
    def div (x,y):
        return(x / y)   
    
    
    main()
    


Answer: Use
[`ast.literal_eval`](https://docs.python.org/3.4/library/ast.html#ast.literal_eval),
it safely evaluates a string as an expression.

Demo:

    
    
    >>> from ast import literal_eval
    >>> a = literal_eval('5')
    >>> b = literal_eval('3.5')
    >>> c = literal_eval('True')
    >>> [e, type(e).__name__ for e in (a, b, c)]
    [(5, 'int'), (3.5, 'float'), (True, 'bool')]
    

