Python [conda env:PY27_Test]
Python [conda env:PY36]

Getting Info About Objects, Declarations, Etc.


In [1]:
# tested in Python 2.7 and 3.6
# output is: "<class 'list'>" in 3.6 and "<type 'list'>" in 2.7 

myTestList = [1,2,3]
print(type(myTestList))
if (str(type(myTestList)) == "<class 'list'>") or (str(type(myTestList)) == "<type 'list'>"):
    print("This is a list")
else:
    print("I don't know what that is.")

myTestStr = "some text."
print(type(myTestStr))  # "<class 'str'>" in Python 3.6, "<type 'str'>" in Python 2.7


<type 'list'>
This is a list
<type 'str'>

In [1]:
def get_object_info(obj):
    # this code written in Python 2.7 and tested in 3.6 (works in both places)
    print("Type is: " + obj.__class__.__name__ + ", " + str(type(obj)))
    print("Module Location (for type): " + "{0}.{1}".format(obj.__class__.__module__, obj.__class__.__name__))

In [3]:
get_object_info(myTestList)  # outputs as "class" in Python 3.6 and "type" in Python 2.7


Type is: list, <type 'list'>
Module Location (for type): __builtin__.list

In [2]:
get_object_info(get_object_info)  # try it on itself
                                  # outputs as "<type 'function'>" in Python 2.7 and "<class 'function'>" in Python 3.6


Type is: function, <type 'function'>
Module Location (for type): __builtin__.function

In [1]:
# tested in Python 2.7
'''getting method resolution order for an object 
 (helps trace class heirarchy as well as order that methods resolve within classes)
'''
print(list.__mro__)

import pandas as pd
df = pd.DataFrame({'disk':[1,2,3,4,5], 'mvFrom':[1,3,2,1,3], 'moveTo':[3,2,1,3,2] })

try:
    # does not work on instances, only classes
    print(df.__mro__)
except Exception as ee:
    print(str(type(ee)) + ":")
    print(ee)
    
# better demo of __mro__ can be found in notebooks about OO and objects


(<type 'list'>, <type 'object'>)
<type 'exceptions.AttributeError'>:
'DataFrame' object has no attribute '__mro__'

In [2]:
# tested in Python 2.7
pd.DataFrame.__mro__


Out[2]:
(pandas.core.frame.DataFrame,
 pandas.core.generic.NDFrame,
 pandas.core.base.PandasObject,
 pandas.core.base.StringMixin,
 object)

In [1]:
# Python 2.7 - type()
LL = [1,2,3]
a = 9
print(type(a))
print(type(LL))


<type 'int'>
<type 'list'>

In [ ]: