News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Where is a list of all of python's `__builtin__` datatypes?

posted on 2024-12-02 22:09     read(632)     comment(0)     like(14)     collect(1)


I'm using comparisons like:

if type( self.__dict__[ key ] ) is str \
    or type( self.__dict__[ key ] ) is set \
    or type( self.__dict__[ key ] ) is dict \
    or type( self.__dict__[ key ] ) is list \
    or type( self.__dict__[ key ] ) is tuple \
    or type( self.__dict__[ key ] ) is int \
    or type( self.__dict__[ key ] ) is float:

I've once discovered, that I've missed the bool type:

or type( self.__dict__[ key ] ) is bool \,

Okay - I wondered which other types I missed?

I've started googling:

  • diveintopython3:

    Python has many native datatypes. Here are the important ones:

    1. Booleans are either True or False.
    2. Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even complex numbers.
    3. Strings are sequences of Unicode characters, e.g. an html document.
    4. Bytes and byte arrays, e.g. a jpeg image file.
    5. Lists are ordered sequences of values.
    6. Tuples are ordered, immutable sequences of values.
    7. Sets are unordered bags of values.
    8. Dictionaries are unordered bags of key-value pairs.

Why is that everywhere people are talking about many types, but I can't find a list of all of them? It's almost always only about important ones


solution


You can iterate over __builtin__'s __dict__, and use isinstance to see if something is a class:

builtins = [e for (name, e) in __builtin__.__dict__.items() if isinstance(e, type) and e is not object]
>>> builtins
[bytearray,
 IndexError,
 SyntaxError,
 unicode,
 UnicodeDecodeError,
 memoryview,
 NameError,
 BytesWarning,
 dict'
 SystemExit
 ...

(Note that as @user2357112 pointed out in the excellent comment, we are explicitly excluding object, as it is not useful.)

Note also that isinstance can take a tuple as the second argument, which you can use instead of your series of ifs. Consequently, you can write things like so:

builtins = tuple([e for (name, e) in __builtin__.__dict__.items() if isinstance(e, type) and not isinstance(object, e)])
>>> isinstance({}, builtin_types)
True


Category of website: technical article > Q&A

Author:qs

link:http://www.pythonblackhole.com/blog/article/247238/71b3b599b8ad1136495a/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

14 0
collect article
collected

Comment content: (supports up to 255 characters)