How does Python interpreter look for types? -


if write like:

>>> = float() 

how python interpreter know type 'float'?

i know 'float' variable defined in lib/types.py , refers built-in type types.floattype. how interpreter build complete list of possible types script (including user-defined , imported-module-defined)? places in? , do build such list inside python script?

in question, wrote "how interpreter build complete list of possible types" - contains false assumption. there no complete list of possible types. there effective set of existing types, not arranged in list.

you have namespace, typically looks in order: function (locals), module (globals), builtins. in parsing code compiler selects type constructors literals. every name @ each place refer object, among lot types:

>>> [name name in dir(__builtins__)       if isinstance(getattr(__builtins__,name), type)] ['arithmeticerror', 'assertionerror', 'attributeerror', 'baseexception',   'buffererror', 'byteswarning', 'deprecationwarning', 'eoferror',   'environmenterror', 'exception', 'floatingpointerror', 'futurewarning',   'generatorexit', 'ioerror', 'importerror', 'importwarning', 'indentationerror',   'indexerror', 'keyerror', 'keyboardinterrupt', 'lookuperror', 'memoryerror',   'nameerror', 'notimplementederror', 'oserror', 'overflowerror',   'pendingdeprecationwarning', 'referenceerror', 'runtimeerror', 'runtimewarning',   'standarderror', 'stopiteration', 'syntaxerror', 'syntaxwarning', 'systemerror',   'systemexit', 'taberror', 'typeerror', 'unboundlocalerror', 'unicodedecodeerror',   'unicodeencodeerror', 'unicodeerror', 'unicodetranslateerror', 'unicodewarning',   'userwarning', 'valueerror', 'warning', 'zerodivisionerror', 'basestring',   'bool', 'buffer', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict',   'enumerate', 'file', 'float', 'frozenset', 'int', 'list', 'long', 'memoryview',   'object', 'property', 'reversed', 'set', 'slice', 'staticmethod', 'str', 'super',   'tuple', 'type', 'unicode', 'xrange'] 

the interpreter isn't interested in how many types there are, how each apply interpreting code run. finds using type pointer, every object has:

>>> type(1) <type 'int'> 

the result if 2 types don't fit, it's job tell you:

>>> 1+"foo" traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: unsupported operand type(s) +: 'int' , 'str' >>> "foo"+1 traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: cannot concatenate 'str' , 'int' objects >>> 

the first + int.__add__, , second str.__add__, looked via object on left. (it gets little more complex alternate attempts __radd__, basic principle same.)


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -