Application of Python 3 vars

A collection of advanced code for the Python 3.x built-in function vars.

Copy using dictionary comprehension

Since the return value of vars is a dictionary, it can be copied with ʻitems () and dictionary comprehension. The element of ʻitems () (here ʻitem`) is a tuple of keys and values.

import sys
from pprint import pp

dict1 = {item[0]: item[1] for item in vars(sys).items()}
pp(dict1)

output


{'__name__': 'sys',
 '__doc__': 'This module provides access to some objects ...,
 ...

Note: The return value of the vars built-in function is dictionary type (<class'dict'> ). You must use vars (sys) .items () to enumerate the elements (tuples of keys and values). When for item in vars (sys) is set, it is treated as vars (sys) .keys (), and a dictionary with the first character of the key as the key and the second character as the value is created.

Create a dictionary of key and value types

import sys
from pprint import pp

dict1 = {item[0]: type(item[1]) for item in vars(sys).items()}
pp(dict1)

output


{'__name__': <class 'str'>,
 '__doc__': <class 'str'>,
 '__package__': <class 'str'>,
 '__loader__': <class 'type'>,
 ...

Enumerate value types

import sys
from pprint import pp

set1 = {type(value).__name__ for value in vars(sys).values()}
pp(set1)

output


{'ModuleSpec',
 'NoneType',
 'SimpleNamespace',
 'TextIOWrapper',
 'bool',
 'builtin_function_or_method',
 'dict',
 'flags',
 'float_info',
 'function',
 'hash_info',
 'int',
 'int_info',
 'list',
 'str',
 'thread_info',
 'tuple',
 'type',
 'version_info'}

--The type name can be obtained with type (...) .__ name__. --{e for e in v} is a set comprehension.

Count the number of occurrences of value types


import sys
from collections import Counter
from pprint import pp

counter = Counter((type(value).__name__ for value in vars(sys).values()))
pp(counter)

output


Counter({'builtin_function_or_method': 42,
         'str': 16,
         'TextIOWrapper': 6,
         'int': 5,
         'list': 5,
         'dict': 3,
         'tuple': 2,
         'NoneType': 2,
         'type': 1,
         'ModuleSpec': 1,
         'float_info': 1,
         'int_info': 1,
         'hash_info': 1,
         'version_info': 1,
         'SimpleNamespace': 1,
         'flags': 1,
         'thread_info': 1,
         'bool': 1,
         'function': 1})

Get only built-in functions / methods

import sys
import types
from pprint import pp

dict1 = {item[0]: item[1] for item in vars(sys).items()
         if isinstance(item[1], types.BuiltinFunctionType)}
pp(dict1)

output


{'addaudithook': <built-in function addaudithook>,
 'audit': <built-in function audit>,
 'breakpointhook': <built-in function breakpointhook>,      
 'callstats': <built-in function callstats>,
 '_clear_type_cache': <built-in function _clear_type_cache>,
 ...

Get other than built-in functions / methods

import sys
import types
from pprint import pp

dict1 = {item[0]: item[1] for item in vars(sys).items()
         if not isinstance(item[1], types.BuiltinFunctionType)}
pp(dict1)

output


{'__name__': 'sys',
 '__doc__': 'This module provides ...',
 '__package__': '',
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__spec__': ModuleSpec(name='sys', loader=<class '_frozen_importlib.BuiltinImporter'>),
 ...

Cut to a suitable length

import sys
import types
from pprint import pp
from typing import Optional


def str_truncate_singleline(s, width: int, linesep: Optional[str]):
    s = str(s)
    if not isinstance(width, int):
        raise TypeError()
    addsEllipsis: bool = False
    if linesep is not None:
        i: int = s.find(linesep)
        if i != -1:
            s = s[0:i]
            addsEllipsis = True
    if len(s) + len("...") > width:
        return s[0:width-len("...")] + "..."
    return s + "..." if addsEllipsis else s


dict1 = {item[0]: str_truncate_singleline(item[1], 50, "\n")
         for item in vars(sys).items()
         if not isinstance(item[1], types.BuiltinFunctionType)}
pp(dict1)

Recommended Posts

Application of Python 3 vars
Introduction of Python
Basics of Python ①
Copy of python
Introduction of Python
Python: Application of image recognition using CNN
[Python] Operation of enumerate
List of python modules
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
Unification of Python environment
Copy of python preferences
Basics of Python scraping basics
[Introduction to Udemy Python 3 + Application] 19. Copy of list
[python] behavior of argmax
Usage of Python locals ()
the zen of Python
Installation of Python 3.3 rc1
# 4 [python] Basics of functions
Basic knowledge of Python
Sober trivia of python3
Summary of Python arguments
Python application: Pandas # 3: Dataframe
Various processing of Python
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments
[Introduction to Udemy Python3 + Application] 52. Tupleization of positional arguments
[Python] Correct usage of map
Python application: Pandas Part 1: Basic
Python application: Pandas Part 2: Series
Towards the retirement of Python2
Summary of python file operations
Summary of Python3 list operations
Python --Quick start of logging
Recommendation of binpacking library of python
[python] Value of function object (?)
Automatic update of Python module
Python --Check type of values
[Python] Etymology of python function names
About the ease of Python
Static analysis of Python programs
About various encodings of Python 3
Equivalence of objects in Python
Introduction of activities applying Python
python> Handling of 2D arrays
Install multiple versions of Python
Version upgrade of python Anaconda
Handling of python on mac
python: Basics of using scikit-learn ①
Python application: data visualization # 2: matplotlib
Comparison of 4 Python web frameworks
Application of CNN2 image recognition
Simple FPS measurement of python
Check OpenSSL version of python 2.6
Python implementation of particle filters
[Python] Copy of multidimensional list
Faster loading of Python images
Sample usage of Python pickle
Web application with Python + Flask ② ③
Basic usage of Python f-string
Implementation of quicksort in Python
[Python] Correct usage of join
Source installation and installation of Python