Recognizing a variable as a string in a module

Following other posts, I have a function that displays information about a variable based on its name. I would like to move it to 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 oshape () function in a module so that it can be reused. However, placement in the module does not allow access to global elements from the main module. I tried things like "import __main__" and even saved the globals () function and passed it to the submodule. The problem is that globals () is one function that specifically returns the global values โ€‹โ€‹of the module from which it is called, and not for each function.

 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' 

Additional Information: The goal is to reduce redundant typing. With a little modification (I took it to simplify the question), oshape could report a list of variables, so I could use it like:

 oshape('a', 'b', 'other_variables_i_care_about') 

Therefore, solutions that require entering variable names twice, in fact, are not what I'm looking for. In addition, simply passing in a variable does not allow the name to be printed. Consider using this in a long log file to show the results of calculations and checking the size of variables.

+5
source share
2 answers

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 
+1
source

The real problem you are facing here is the namespace problem.

You can write your method this way:

 def oshape(name, x): # output the name, type and shape/length of the input variable(s) # for array or list if type(x) in (np.array, 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(x))) 

and use it as follows:

 import numpy as np import olib a=np.array([1,2,3]) b=[4,5,6] olib.oshape('a', a) olib.oshape('b', b) 

but it looks very redundant to have the variable and its name in the arguments.

Another solution would be to give globals() dict to the method and save your code.

See this answer on the visibility of global variables through modules.

+2
source

All Articles