1
\$\begingroup\$

Background

I wrote a a couple functions that make it possible to generate a list of attributes for any given object that has them. I use the list that is objectWalker generates in other functions mostly centered around pandas DataFrame analysis. Please tear this code apart I'd like to hear whatever you have to say.

Code

def inspectObject(obj):
    """Return list of object attributes and their types.

    Parameters
    ----------
    obj: :obj:
        Any kind of object that is not a builtin.

    Returns
    -------
    obj_ids: list
        A list of lists to be specific.
    """
    obj_ids = []
    # Make list of builtins
    # bi_list = dir(__builtins__)
    # Try to make a list of the types of things inside obj.
    try:
        # Make list all things inside of an object
        for name, thing in obj.__dict__.items():
            obj_ids.append([name, type(thing).__name__, thing])

        return obj_ids

    except Exception:
        pass


def objectWalker(obj, desired_type=None, att_list=None):
    """Recursively walks through an object an genrates a list of its attributes.

    Parameters
    ----------
    obj: :obj:

    desired_type: str

    Returns
    -------
    att_list: list

    """
    # Create an attributes list if none has been asigned.
    if att_list is None:
        att_list = []

    # Create list of types that we do not want yo serch through
    no_list = dir(__builtins__)
    no_list.append("DataFrame")
    # desired_type = desired_type or "DataFrame"

    obj_inspect = inspectObject(obj)

    for i in obj_inspect:

        # Test if object attribute is desired_type.
        if re.search(desired_type, i[1], re.I) is not None:

            att_list.append(i)

        # If the object attribute is not the desired_type then...
        elif i[1] not in no_list:
            # Try to use recursively objectWalker on the object.
            try:
                objectWalker(obj.__dict__[i[0]], desired_type, att_list)
            except Exception:
                pass
    return att_list

UPDATE

So I guess this is the best way to do it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.