Home > Enterprise >  Python - Get name list of objects of a specified class in the namespace
Python - Get name list of objects of a specified class in the namespace

Time:08-09

I want to get a list of all dictionary objects that exist in the namespace. I know that %whos() magic function will print the list, but as far as I could tell, it just prints and doesn't return anything.

CodePudding user response:

Here is one function that would return a dataframe with variable names and their respective classes, which makes is filterable as well:

#%%% Objects in namespace

import pandas as pd

def get_env_vars(filter_for=None):
    globals_list = globals()
    var_list = [k for k in globals_list.keys() if (not k.startswith('_')) & (k not in ['In','Out','get_ipython','exit','quit'])]
    var_df = pd.DataFrame({'VarName': var_list})
    var_types = []
    for z in var_list:
        var_types.append(type(globals()[z]))
    var_df['VarClass'] = var_types
    var_df['VarClass'] = var_df['VarClass'].apply(lambda x: str(x).replace("<class '", "").replace("'>", ""))
    if not pd.isna(filter_for):
        filter_for = str(filter_for).replace("<class '", "").replace("'>", "") if not isinstance(filter_for, str) else filter_for
        var_df = var_df[var_df['VarClass'] == filter_for].reset_index(drop=True)
        
    return var_df

Example:

a = 3
b = [1,2,3]
c = ['a','b']
d = {'a': 1, 'b': 2}

get_env_vars()

>>> OUTPUT
#         VarName  VarClass
# 0            pd    module
# 1  get_env_vars  function
# 2             a       int
# 3             b      list
# 4             c      list
# 5             d      dict

Get list objects only

get_env_vars('list')

>>> OUTPUT
#   VarName VarClass
# 0       b     list
# 1       c     list
  • Related