Your logic is much more complicated, you just have to pass the arrays themselves, since you also pass the variable name as a string so as not to look for something you don't have access to. But if you want your code to work just like you could set attibute in a module:
import numpy as np import olib a = np.array([1, 2, 3]) b = [4, 5, 6] olib.a = a olib.b = b olib.oshape('a') olib.oshape('b')
This will lead to any arguments and searches for the module from which the code for attrs is executed:
import numpy as np import sys from os.path import basename import imp def oshape(*args): # output the name, type and shape/length of the input variable(s) # for array or list file_name = sys.argv[0] mod = basename(file_name).split(".")[0] if mod not in sys.modules: mod = imp.load_source(mod, file_name) for name in args: x = getattr(mod, 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('{} {} X'.format(name, type(x)))
Just pass the lines with the variable names:
:~/$ cat t2.py import numpy as np from olib import oshape a = np.array([1, 2, 3]) b = [4, 5, 6] c = "a str" oshape("a", "b", "c") :$ python t2.py a <type 'numpy.ndarray'> (3,) b <type 'list'> 3 c <type 'str'> X
source share