What to do when the value type is ambiguous in Python?

What if there are times when you cannot guarantee or prove that you have 100% control over the type of a value?

Is there a convenient way to write something like type inference? If anyone knows, please let me know. Is it possible to convert dict to struct? What is good? I felt that the ambiguous type was annoying **, so I decided to think again.

Example

Suppose you have dict data called test as in the example below. I want to check if there is a 1 in the key of each value of the test variable.

test_dict_key_value_type.py


test = {
    0: {'key': [1, 2, 3]},
    1: {'key': None},
    2: {'key': []},
    3: {},
    4: None,
}

#Pattern 1 Use is instance to check type and use get to determine
for k, v in test.iteritems():
    if v is not None and isinstance(v.get('key'), list) and 1 in v.get('key'):
        print k, ':found!'


#Pattern 2 Prepare a function to redefine the data
def set_default_dict_value_type(test, dict_value_key, dict_value_type):
    for k, v in test.iteritems():
        if v is None or not isinstance(v.get(dict_value_key), dict_value_type):
            test[k] = {
                dict_value_key: dict_value_type()
            }
    return test
# new_Since all the key values of test are dict, they can be used only with the get method.
for k, v in set_default_dict_value_type(test.copy(), 'key', list).iteritems():
    if 1 in v.get('key'):
        print k, ':found!'


#Pattern 3 Try and ignore
for k, v in test.iteritems():
    try:
        if 1 in v.get('key'):
            print k, ':found!'
    except:
        pass

Try to run

bash


$ python test_dict_key_value_type.py
0 :found!
0 :found!
0 :found!

Summary

In this case, if you think about it carefully, the problem is that the definition of data is ambiguous **. So I came to the conclusion that ** redefining the data type would solve the problem **. In other words, if the type is different from the schedule, it is considered that the data is corrupted, and it is okay to redefine the type. In the above case, Case 2 is the preferred method at this stage.

Task

Sample module

I made a sample module that checks list and dict. Are there any improvements yet?

data_type.py


#!/usr/bin/env python


def set_dict_key_value(dic, dict_value_key, dict_value_type):
    """
    :param dict dic: dict data to test
    :param str dict_value_key: dict value key name
    :param Type dict_value_type: Type Object ex. dict, list...
    :rtype: dict
    :return: redefined dict data

    ex.
    >>> test = {
        0: {'key': [1, 2, 3]},
        1: {'key': None},
        2: {'key': []},
        3: {},
        4: None,
    }
    >>> set_dict_key_value(test, 'key', list)
    {
        0: {'key': [1, 2, 3]},
        1: {'key': []},
        2: {'key': []},
        3: {'key': []},
        4: {'key': []}
    }
    """
    new_dic = dic.copy()
    for k, v in new_dic.iteritems():
        if v is None or not isinstance(v.get(dict_value_key), dict_value_type):
            new_dic[k] = {dict_value_key: dict_value_type()}
    return new_dic


def set_list_value(lst, list_value_type, default_none_value=None):
    """
    :param list lst: list data to test
    :param Type list_value_type: Type Object ex. dict, list,,,
    :param not None clean_list_default_value: Any type of data except for None
    :rtype: list
    :return: redefined list data

    ex.
    >>> a = [None, 1, 'str', False, 1.0, {1: 0}]
    >>> set_list_value(a, dict, {})
    [{}, {}, {}, {}, {}, {1: 0}]
    """
    return map(
        lambda v: v if isinstance(v, list_value_type) else list_value_type(),
        lst if default_none_value is None else
        clean_list_none_value(lst, default_none_value)
    )


def clean_list_none_value(lst, default_none_value):
    """
    Replace None with defalut_none_value

    :param list lst: list data to test
    :param not None default_none_value: Any type of data except for None
    :rtype: list
    :return: cleaned list data
    """
    return map(lambda v: default_none_value if v is None else v, lst)

Recommended Posts

What to do when the value type is ambiguous in Python?
What to do when the warning "The environment is in consistent ..." appears in the Anaconda environment
[Python] Type Error:'WebElement' object is not iterable What to do when an error occurs
What to do when is not in the sudoers file.This incident will be reported.
What to do when only the window is displayed and nothing is displayed in pygame Note
What to do if the progress bar is not displayed in tqdm of python
What is "mahjong" in the Python library? ??
What to do when ModuleNotFoundError: No module named'XXX' occurs in Python
What is wheezy in the Docker Python image?
What to do to get google spreadsheet in python
What to do if there is a decimal in python json .dumps
[Python] What is a formal argument? How to set the initial value
[Python] What to do when an error related to SSL authentication is returned
After all, what should I use to do type comparisons in Python?
What is the fastest way to create a reverse dictionary in python?
What to do when a warning message is displayed in pip list
NameError: global name'dot_parser' is not defined and what to do when it comes up in python
What I do when imitating embedded go in python
[openpyxl] What to do when IllegalCharacterError appears in pandas.DataFrame.to_excel
curl: (60) What to do when Issuer certificate is invalid.
What to do when raise ValueError, "unsupported hash type"
What to do when a warning appears around Python integration in Neovim's CheckHealth
How to write what to do when an application is first displayed in Qt for Python with Designer
What to do if PyInstaller3.5 gives an error in Python3.8 (TypeError: an integer is required (got type bytes))
What to do when "cannot import name xxx" [Python]
What to do if abort is displayed when inputting camera video in OpenCV
What to do when the graph does not appear in jupyter (ipython) notebook
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
I want to do something in Python when I finish
What to do when you can't bind CaboCha to Python
What to do when python3 type venv does not work well on Raspberry Pi
[Python] What to do when No module named'pyproj.datadir' appears when Exe is done with PyInstaller
What to do if the print command itself causes an error in Maya python
What to do if you get an error when importing matplotlib in Python (Mac)
What to do if Python IntelliSense is not displayed in VS Code on Windows
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
What to do if Python does not switch from the System version in pyenv
What to do if you can't hit the arrow keys in the Python interactive console
I want to initialize if the value is empty (python)
What to do if ʻarguments [0] .scrollIntoView ();` fails in python selenium
What to do when Japanese is not displayed on matplotlib
Master the type in Python? (When should type check be done)
How to get the last (last) value in a list in Python
What to do when "Invalid HTTP_HOST header" appears in Django
[Python] What is @? (About the decorator)
In the python command python points to python3.8
[python] What is the sorted key?
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3
What to do with PYTHON release?
What is the python underscore (_) for?
What to do if the image is not displayed using matplotlib etc. in the Docker container
What to do when a Missing artifact occurs in a jar that is not defined in pom.xml
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
[AWS] What to do when the ping command causes a "timeout"
Be careful when specifying the default argument value in Python3 series
[Introduction to Python] What is the most powerful programming language now?
How to give and what the constraints option in scipy.optimize.minimize is
[Python] Execution time when a function is entered in a dictionary value
Timezone specification when converting a string to datetime type in python
How to use the asterisk (*) in Python. Maybe this is all? ..
What to do if Insecure Platform Warning appears when running Python