Python 2.7 using function input as string and variable

I would like to do the following:

print "CC =",CC 

but as a function, so I have to write the CC variable only once. I cannot figure out how to do this in a function, since it always evaluates CC as a floating point number (what is it) .... Is there a way to accept the input of a function as a string or as a floating point number?

I tried this:

 def printme(a): b='%s' % a print b return b 

but, of course, he prints only the value of a , not his name.

+6
source share
7 answers

You can use the inspect module (see also this SO question ):

 def printme(x): import inspect f = inspect.currentframe() val = f.f_back.f_locals[x] print x, '=', val CC = 234.234 printme('CC') # <- write variable name only once # prints: CC = 234.234 
+3
source

Perhaps the dictionary is the best approach to the problem. Assuming you have several name-value pairs that you want to use, you can put them in a dict :

 params = {"CC": 1.2345, "ID": "Yo!", "foo": "bar"} 

Then, for example, you can print all the names and values โ€‹โ€‹well formatted as follows:

 for key in params: print "{0} = {1}".format(key, params[key]) 

But since it is still unclear why you are trying to do this, it is difficult to say if this is correct.

+1
source

I think this is your required solution:

 def printme(x): keys_list = [key for key, value in globals().iteritems() if value == x] print keys_list for key in keys_list: if id(globals()[key]) == id(x): result = "%s = %s" %(key, x) print result break return result 

for example, if you declare a variable:

 >>> c=55.6 

then printme (c) result will be

 >>> 'c = 55.6' 

Note. This solution is based on a globally unique identifier mapping.

+1
source

If you understood correctly that you want something like that?

 def f(a): print('{0}: = {1}'.format(locals().keys()[0], a)) 

Update:

I know this example does not make much sense, since it is basically the same as:

 def f(a): print('a: {0}'.format(a)) 

I just wanted to point the OP to locals (), since I did not quite understand what it was trying to execute.

I think this is more than what he is looking for:

 def f(**kwargs): for k in kwargs.keys(): print('{0}: {1}'.format(k, kwargs[k])) f(a=1, b=2) 
0
source

Not quite what you want, but easy to do:

 def printme(**kwargs): for key, value in kwargs.items(): print '%s=%s' % (key, value) return value In [13]: printme(CC=1.23, DD=2.22) CC=1.23 DD=2.22 Out[13]: 1.23 
0
source

If you understood correctly that you want to get an abbreviated name for printing the variable name and its value in the current area? This is generally not possible without using the trace trace function or sys._getframe , which in general should only be used if you know what you are doing. The reason for this is because the print function has no other way to get locales from the call area:

 def a(): x = 1 magic_print("x") #will not work without accessing the current frame 

What you can do without them explicitly passes this function to local users:

 def printNameAndValue(varname, values): print("%s=%s" % (varname, values[varname])) def a(): x = 1 printNameAndValue("x", locals()) #prints 'x=1' 

EDIT:

See catchemifyoutry answer for a solution using a validation module (which internally uses sys._getframe). For completeness, a solution that uses the trace function directly is useful if you are using python 2.0 and the check is not available;)

 from sys import settrace __v = {} #global dictionary that holds the variables def __trace(frame, event, arg): """ a trace function saving the locals on every function call """ global __v if not event == "call": return __trace __v.update(frame.f_back.f_locals) def enableTrace(f): """ a wrapper decorator setting and removing the trace """ def _f(*a, **kwa): settrace(__trace) try: f(*a, **kwa) finally: settrace(None) return _f def printv(vname): """ the function doing the printing """ global __v print "%s=%s" % (vname, __v[vname]) 

Save it in the module and use it like this:

 from modulenamehere import enableTrace, printv @enableTrace def somefunction(): x = 1 [...] printv("x") 
0
source

To achieve this, a global variable is used, func.__globals__.keys() contains all the variables passed to func , so I filtered the name startin with __ and saved them in a list. every time func() called, func() func.__globals__.keys() updated with the new variable name, so compare the new varn with the old glo results with the new variable added.

 glo=[] def func(x): global glo varn=[x for x in func.__globals__.keys() if not x.startswith('__') and x!=func.__name__] new=list(set(varn)^set(glo)) print("{0}={1}".format(new[0],x)) glo=varn[:] 

exit:

 >>> a=10 >>> func(a) a=10 >>> b=20 >>> func(20) b=20 >>> foo='cat' >>> func(foo) foo=cat >>> bar=1000 >>> func(bar) bar=1000 
0
source

Source: https://habr.com/ru/post/919494/


All Articles