Following other posts here, I have a function that prints out information about a variable based on its name. I would like to move it into a module.
#python 2.7
import numpy as np
def oshape(name):
#output the name, type and shape/length of the input variable(s)
#for array or list
x=globals()[name]
if type(x) is np.array or type(x) is np.ndarray:
print('{:20} {:25} {}'.format(name, repr(type(x)), x.shape))
elif type(x) is list:
print('{:20} {:25} {}'.format(name, repr(type(x)), len(x)))
else:
print('{:20} {:25} X'.format(name, type(t)))
a=np.array([1,2,3])
b=[4,5,6]
oshape('a')
oshape('b')
Output:
a <type 'numpy.ndarray'> (3,)
b <type 'list'> 3
I would like to put this function oshape() into a module so that it can be reused. However, placing in a module does not allow access to the globals from the main module. I have tried things like 'import __main__ ' and even storing the function globals() and passing it into the submodule. The problem is that globals() is one function, which specifically returns the globals of the module it is called from, not a different function for each module.
import numpy as np
import olib
a=np.array([1,2,3])
b=[4,5,6]
olib.oshape('a')
olib.oshape('b')
Gives me:
KeyError: 'a'
Extra information: The goal is to reduce redundant typing. With a slight modification (I took it out to make it simpler for the question), oshape could report on a list of variables, so I could use it like:
oshape('a', 'b', 'other_variables_i_care_about')
So solutions that require typing the variable names in twice are not really what I am looking for. Also, just passing in the variable does not allow the name to be printed. Think about using this in a long log file to show the results of computations & checking variable sizes.