Convert variable names to strings? - drawing pen (2023)

Questions :

I want to convert a python variable name to its string equivalent as shown. Any idea how?

Variable = {}press???# want to see 'var'something_other =3press???# imprimiria 'something_else'

Responder :

TL; EN: That's not possible. See "Conclusion" at the end.

There is a usage scenario where you might need this. I'm not saying that there aren't better ways or that the same functionality isn't achieved.

This would be useful for "offloading" an arbitrary list of dictionaries on errors, debug modes, and the like.

What would be needed is the reverse of thatEvaluate()Function:


which would take an identifier name ('variable', 'dictionary', etc.) as an argument and return a

String containing the name of the identifier.

Consider the following current situation:

random function (data argument)

If you pass an identifying name ('function', 'variable', 'dictionary', etc.)data argumentyetrandom_function()(another identifier name), you actually pass an identifier (eg:<argument data object at 0xb1ce10>) to another identifier (for example:<random_function function at 0xaffff78>):

< function random function in0xafff78>(< data argumentObjectEm0xb1ce10>)

As I understand it, only the memory address is passed to the function:

< function activated0xafff78>(<ObjectEm0xb1ce10>)

So you would have to pass a string as an argument torandom_function()so this function has the name of the argument identifier:

random_function('data argument')

Inside the random() function

definitive random_function(first_argument):

, one would use the already provided string'data argument'A:

  1. serve as a 'name identifier' (to view, log, split/concatenate strings, etc.)

  2. feed-themEvaluate()Function to get a reference to the real identifier and therefore a reference to the real data:

    press("Currently in progress", first_argument)some_internal_var =Evaluate(first_argument)press("here comes the data:"+to connect(some_internal_var))

Unfortunately, this doesn't work in all cases. It only works if therandom_function()can solve this'data argument'String to an actual identifier. That means. Yesdata argumentThe name of the identifier is available on therandom_function()namespace.

This is not always the case:

# principal1.pyObjectsome_module1argument_data ='My data'some_module1.random_function('data argument')# algun_modulo1.pydefinitive random_function(first_argument):press("Currently in progress", first_argument) some_internal_var =Evaluate(first_argument)press("here comes the data:"+to connect(some_internal_var))######

The expected results would be:

Currently in progress: data_argument here comes the data: my data

Becausedata argumentIdentifier name is not available onrandom_function()namespace, this would produce the following:

Currently working on argument_dataTraceback (last recent call): File"~/", line6,Em<Modul> some_module1.random_function('data argument') File"~/", line4,Emrandom_function some_internal_variable =Evaluate(first_argument) file"<string>", line1,Em<module> name error: name'data argument' es NOare defined

Now consider the hypothetical use of aget_identifier_name_missing_function()which would behave as described above.

Here is dummy code from Python 3.0: .

# principal2.pyObjectsome_module2some_dictionary_1 = {'definition_1':'Text 1','definition_2':'text_2','etc':'etc.'}some_other_dictionary_2 = {'key_3':'valor_3','key_4':'valor_4','etc':'etc.'}## more stuff like that#some_other_dictionary_n = {'random_n':'random_n','etc':'etc.'}foreach_of_my_dictionariesEm( some_dictionary_1, some_other_dictionary_2, ..., some_other_dictionary_n ): some_module2.some_function(any_one_of_my_dictionaries)# algun_modulo2.pydefinitive some_function(a_dictionary_object):for_key valueEma_dictionary_object.items():press(get_indentifier_name_missing_function(a_dictionary_object) +" "+to connect(_clave) +" = "+to connect(_valor) )######

The expected results would be:

some_dictionary_1 definition_1 = text_1some_dictionary_1 definition_2 = text_2some_dictionary_1 etc = etc.some_other_dictionary_2 key_3 = value_3some_other_dictionary_2 key_4 = value_4some_other_dictionary_2 etc = etc...............some_other_dictionary_n random_otronal_n = etc_n = etc.

unfortunately,get_identifier_name_missing_function()You would not see the names of the 'original' identifiers (any_dictionary_,another_dictionary_2,some_other_dictionary_n). I would just see thema_dictionary_objectidentifier name.

So the actual result would be more like:

a_dictionary_object definition_1 = texto_1a_dictionary_object definition_2 = texto_2a_dictionary_object etc = etc.a_dictionary_object key_3 = value_3a_dictionary_object key_4 = value_4a_dictionary_object etc = etc........a_dictionary_object random_n = random_na_dictionary_object etc = etc.

then vice versaEvaluate()The function is not that useful in this case.

Currently you would have to do this:

(Video) I Played MrBeast's Song in Space

# as above except: foreach_of_my_name_dictionariesEm('some_dictionary_1','some_other_dictionary_2','...','some_other_dictionary_n'): some_module2.some_function( { each_one_of_my_dictionaries_names :Evaluate(any_one_of_my_dictionary_names) } )# definitive some_function(contêiner a_dictionary_name_object):for_dictionary name, _dictionary objectEma_dictionary_name_object_container.items():for_key valueEm_dictionary_object.elements():press(to connect(_dictionary name) +" "+to connect(_clave) +" = "+to connect(_valor) )######


  • Python just passes memory addresses as arguments to functions.
  • Strings representing the name of an identifier can only be referenced by the actual identifierEvaluate()Function if the name identifier is available in the current namespace.
  • A hypothetical reversal ofEvaluate()function, it would not make sense in cases where the calling code does not directly "see" the identifier name. For example, within each function called.
  • Currently you have to transition to a function:
    1. the string representing the name of the identifier
    2. the actual identifier (memory address)

This can be achieved by passing both'Chain'jeval('string')at the same time as the called function. I think this is the most "general" way to solve this chicken's egg problem through arbitrary functions, modules and namespaces without using corner case solutions. The only disadvantage is the use ofEvaluate()Feature that can easily lead to insecure code. Care must be taken not to feed them.Evaluate()It works with almost anything, especially unfiltered external input data.

Answer 2:

Fully possible with the python-varname (python3) package:

vonvariable nameObjectnames ='No!'press(Name of)



To install:

pip3 install variable name

Or purchase the package here:

Answer 3:

I looked up this question because I wanted a Python program to print assignment statements for some of the program's variables. For example, it might print "foo=3, bar=21, baz=432". The print function would need the variable names in string form. I could have marked up my code with the strings "foo", "bar", and "baz", but I felt like I was repeating myself. After reading the previous answers I found the following solution.

The globals() function behaves like a dict with variable names (in the form of strings) as keys. I wanted to retrieve from globals() the key corresponding to the value of each variable. The globals().items() method returns a list of tuples; In each tuple, the first element is the variable name (as a string) and the second is the variable value. My variablename() function searches this list to find the variable names that match the value of the variable whose name I need as a string.

The itertools.ifilter() function performs the search by testing each tuple in the globals().items() list with the itertools.ifilter() function.Lambda x: var is global()[x[0]]. In this function, x is the tuple to be tested; x[0] is the variable name (as a string) and x[1] is the value. The Lambda function tests whether the value of the tested variable matches the value of the variable passed to variablename(). actually usingesoperator, the Lambda function checks that the tested variable name is bound to the exact same object as the variable passed to variablename(). In this case, the tuple passes the test and is returned by ifilter().

The itertools.ifilter() function actually returns an iterator that does not return any results until successfully called. So that it can be called correctly I put it in a list comprehension[tpl[0] para tpl ... globals().elements())]. List comprehension stores only the variable nametpl[0], ignoring the value of the variable. The created list contains one or more names (as strings) linked to the value of the variable passed to variablename().

The uses of variablename() shown below return the desired string as an item in a list. In many cases, it will be the only item on the list. However, if another variable name is given the same value, the list will get longer.

>>>definitive variable name(eras):... Objectitertools... give back[tpl[0]forPleaseEm ...itertools.filter(lambdaX: yesesX[1],global().Elements())]...>>>Variable = {}>>>VariableName(var)['eras']>>>something_other =3>>>variable name (something else)['anything else']>>>yet_other =3>>>variable name (something else)['Yet another','anything else']

Answer 4:

As long as it's a variable and not a second class, this works for me:

definitive print_var_name(Variable):forNameEm global():E Evaluate(Name) == Variable:pressfooname =123print_var_name(foo)>>>foo

This happens to class members:

Classroom xyz:definitive __darin__(to be):to allowmembro = xyz()print_var_name(membro)>>>membro

and this for classes (as an example):

abc = xyzprint_var_name(abc)>>>abc>>>xyz

So for the classes you get the name AND the properties.

Answer 5:

That's not possible.

There really isn't a "variable" in Python. What Python really has are "names" that objects can be linked to. The object doesn't care what names it can be linked to. It can be associated with dozens of different names or none at all.

Consider this example:

foo =1barra =1baz =1

Now let's say you have every object with value 1 and you want to work backwards and find its name. What would you print? Three different names are associated with this object and all are equally valid.

In Python, a name is a way of accessing an object, so there's no way to work with names directly. There might be a clever way to hack python bytecodes or something to get the name value, but this is parlor trick at best.

if you know what you wantprint foopress"fu", you can also just walkprints "foo"First.

EDIT: Changed the text a bit to make this clearer. Again, here's an even better example:

foo =1bar = foobaz = foo

In practice, Python uses the same object for integers with common values ​​like 0 or 1, so the first example would bind the same object to all three names. But this example is very clear: the same object is bound to foo, bar and baz.

(Video) LESSON 5: Working with Strings in Arduino

Answer 6:

Technically, the information is available to you, but how would you put it to good use, as others have asked?

>>>x=52>>>global(){'__built__': <module'__Registered__'(built-Em)>,'__Name__':'__Director__','X':52,'__doc__':none,'__Package__':none}

This shows that the variable name exists as a string in the globals() dictionary.


In this case, it ends up being the third key, but there's no reliable way to tell where a given variable name will end up.

>>>forkEm global().Key():... E NOk. begins with ("_"):... pressk...x>>>

You can filter system variables like this, but still get all your own items. Simply running the code above created another "k" variable that changed the position of "x" in the dict.

But perhaps this is a useful start for you. If you let us know what you want this feature for, we can provide you with other useful information.

Answer 7:

Using thedecompactor:

>>>definitive tostr(**Bedrooms):give backkwargs>>>Variable = {}>>>something_other =3>>>tostr(var = var,something_else=something_else){'eras'= {},'anything else'=3}

Answer 8:

Somehow you must refer to the variable whose name you want to print. So it would look like this:

pressvarname (something else)

There is no such feature, but if there were, it would make no sense. you have to writeanything else, so you can also enter left and right quotes to output the name as a string:

press "anything else"

Answer 9:

What are you trying to achieve? There's absolutely no reason to do what you describe and there's probably a much better solution to the problem you're trying to solve...

The most obvious alternative to what you're asking is a dictionary. For example:

>>>my_data = {'eras':'something'}>>>My data['anything else'] ='something'>>>pressmy_data.keys()['eras','anything else']>>>pressMy data['eras']something

Mainly as a challenge, I implemented the desired result. Please do not use this code!

#!/usr/bin/env python2.6Classroom new facilities:"""Please, never use this code...""" definitive __darin__(i, local_initials): self.prev_locals =List(initial_locals.keys())definitive show_neu(Eu, new_natives): Salida =", ".to connect(List(lower(new_locations) -lower(self.prev_locals))) self.prev_locals =List(new_locals.keys())give backProduction# Attitudeeca =noneeww = New Locations(local people())# code requested "It works"Variable = {}presseww.show_new(local people())# Outputs: Varsomething_other =3presseww.show_new(local people())# outputs: something_other# additional testsandere_variable =4and_a_final_one =5presseww.show_new(local people())# Saídas: other_variable and_one_final_one

Answer 10:

Django doesn't do this when generating field names?

It seems reasonable to me.

Answer 11:

I think this is a cool solution and I think it's the best you can get. But do you see a way to handle ambiguous results your function might return?

SeThe "is" operator behaves unexpectedly with integersFor example, low integers and strings of the same value are cached by Python, so the variablename function can return ambiguous results with high probability.

In my case I want to create a decorator that adds a new variable to a class with the name of the variable I pass:

definitive inject(class, dependency):Class.__dict__["__"+variablename(dependency)]=dependency

But if your method returns ambiguous results, how can I find out the name of the variable I added?

var beliebige_var="mivarcontent"wo myvar="mivarcontent"@inject(Myvar)Classroom false clauses():definitive method my classes(to be):pressI.__mivar# Not sure if this variable is defined...

Perhaps if I also check the local list I can at least remove the "dependency" variable from the list, but that won't be a reliable result.

Answer 12:

Here's a concise twist that lets you specify any directory.

(Video) The most elegant key change in all of pop music

The problem with using directories to find something is that multiple variables can have the same value. So this code returns a list of possible variables.

definitive variable name(eras,directory=local people()):give back[ I likeforkey valueEm directory.Items()E I WENT(Courage) ==I WENT(No)]

Answer 13:

I don't know if it's correct or not, but it worked for me.

definitive variable name(Variable):forNameEm List(global().keys()): expression =Defender({Name})' E I WENT(variable) ==Evaluate(Expression):give backName

Answer 14:

it is possible to some extent. The answer is similar to @tamtam's solution.

The given example is based on the following assumptions:

  • You are looking for a variable by its value
  • The variable has a single value.
  • The value is in the global namespace


testvar ="unique value"varNombreComoCadena = [kforkvEm global().Elements()E=="unique value"]## Variable "varNameAsString" contains all matching variable names# the "single value" value# In this example, it is a single entry list "testVar"#press(varNombreAsString)

You can extend this example to any other variable/data type

Answer 15:

I want to point out a use case that is not an anti-pattern and there is no better way to do this.

This one seems to beloseFunction in Python.

There are several features such aspatch.object, which take the name of a method or property to be fixed or accessed.

Consider this:

patch.object(obj, "method_name", new_reg)

This can cause a "false success" when you change the name of a method. Ie: you might send an error you thought you were testing... simply because of an incorrect refactoring of the method name.

Now consider:variable name. This could be an efficient built-in function. But for now it might work iterating over an object or the caller structure:

Now your call can be:

patch.member(obj, obj.method_name, new_reg)

And the patch function can call:

varname(var, obj=obj)

This: would assert that the var is linked to the obj and would return the name of the member. Or if obj is not specified, use the call-stack framework to derive it, etc.

Eventually it could become an efficient integrated system, but here's a definition that works. I deliberately did not supportbuilt in, but easy to add:

Feel free to put this in a package callednombrevar.pyand use it in your patch.object calls:

patch.object(obj, varname(obj, obj.method_name), new_reg)

Note: This was written for Python 3.

Objectinspectdefinitive _varname_dict(wo, dkt): key name =none forkey valueEmdct.elements():EbravuraesEras:Ekey namees NO none:increasenot implemented error ("No duplicate name %s, %s"%(keyname, key)) keyname = keygive backkey namedefinitive _varname_obj(and, Object): key name =none forI likeEm directory(target): value =to receive(object, key) equals = valueeserasEuntil:Ekey namees NO none:increasenot implemented error ("No duplicate name %s, %s"%(keyname, key)) keyname = keygive backkey namedefinitive variable name(var,obj=none):EObjectes none:E harvest(eras,"__to be__"):give backvar.__name__ caller_frame = inspect.currentframe().f_backto try: ret = _varname_dict(var, caller_frame.f_locals)exceptNameError: ret = _varname_dict(var, caller_frame.f_globals)the rest: ret = _varname_obj(var, obj)Ewithdrawnes none:increaseerror name("Name not found. (Note: Built-in roles are not supported)")give backwithdrawn

Answer 16:

This works for simple data types (str, int, float, list, etc.)

(Video) Drawing with the Pen tool, Pencil tool & Brush tool Ep10/19 [Adobe Illustrator for Beginners]

>>> def my_print(var_str) : print var_str+':', globals()[var_str]>>> a = 5>>> b = ['hola', ',mundo!']>>> my_print('a ')a: 5>>> my_print('b')b: ['hola', ',mundo!']

Answer 17:

It's not very pythonic, but I got curious and found this solution. You must duplicate the global dictionary because its size changes as soon as you define a new variable.

definitive var_to_name(eras):# without PyTypeChecker inspectiondict_vars =dictate(global().elementos()) var_string =none forNameEmdict_vars.keys():Edict_vars[number]esvar : var_string = nomeoveralls give backvar_stringE__name__ =="__Director__": testing =3 press(f" tests ={to test}")press(f"Variable name:{var_to_name(test)}")

which returns:

testing =3Variable name: test

Answer 18:

To get the variable nameerasas a string:

no =1000var_name = [kforkvEm local people().Elements()Ev == var][0]press(var_name)# ---> prints 'var'

Answer 19:

Thanks @restrepo, it was exactly what I needed to create a standard save_df_to_file() function. To do this, I made some minor changes to your tostr() function. Hope this helps someone:

definitive variabletostr(**df): Nomedavariável =List(df.keys())[0]give backvariablename variabletostr(df=0)

Answer 20:

The original question is quite old, but I found onefastSolution using Python 3. (I say almost because I think you can get close to a solution, but I don't think there is a concrete enough solution to meet the exact requirement.)

First, you must consider the following:

  • Objects are a core concept in Python and can be assigned to a variable, but the variable itself is a bound name (think of a pointer or reference), not the object itself.
  • erasIt's just a variable name bound to an object, and that object can have more than one reference (it doesn't show up in your example).
  • in that case,erasseems to be in the global namespace so you can use the globalbuilt inconveniently namedglobal
  • different named references to the same object share the same thingI WENTwhich can be checked by running idbuilt in I WENTAs:identification (where)

This function takes the global variables and filters those that match theContentvariable for you.

definitive get_bound_names(target variable):'''Returns a list of linked object names.''' give back[kfork,vEm global().Elements()Evestarget variable]

The real challenge here is that you are not guaranteed to get the variable name itself. It will be a list, but that list contains the name of the variable you are looking for. If your target variable (bound to an object) is indeed the only name bound, you can access it like this:

bound_names = get_variable_names(target_variable) var_string = bound_names[0]

Answer 21:

Possible for Python >= 3.8 (with string f'{var=}' )

Not sure if this can be used in production code, but in Python 3.8 (and later) it is possibleUse the f' string debug specifier.Adding = to the end of an expression will print the expression and its value:

my_salary_variable =5000press(F'{my_salary_variable = }')Salida:my_salary_variable =5000

To discover this magic, here is another example:

param_list =F'{my_salary_variable=}'.to share('=')press(param_list)Salida:['my_salary_variable','5000']

Explanation: Placing '=' after your var in f'string returns a string containing the variable name, '=' and its value. Split it with .split('=') and you get a list of 2 strings, [0] - your_variable_name and [1] - the actual object of the variable.

Select item [0] from the list if you only need the variable name.

my_salary_variable =5000param_list =F'{my_salary_variable=}'.to share('=')press(param_list[0])Salida:my_salary_variableÖ,Emuma lineamy_salary_variable =5000press(F'{my_salary_variable=}'.to share('=')[0])Salida:my_salary_variable

It also works with the functions:

definitive mi_super_calc_foo(Number):give backNumber**3press(F'{mi_super_calc_foo(5) = }')press(F'{mi_super_calc_foo(5)=}'.to share('='))


mi_super_calc_foo(5) =125['mi_super_calc_foo(5)','125']Complete processswindlerexit code0

Answer 22:

This module converts variable names to a string:

Use like this:

vonvariable nameObjectnumberofvariables=0name=namevon(variable)press(name) // output: variable

Install it by:

pip installation variable name

Answer 23:

press "eras"press "anything else"

Or did you mean something different?


1. Penn and Teller Fool Us // Shin Lim
(Shin Lim)
2. Python creating and casting variables, type(), case sensitive, legal variable names, comments(#).
3. Calum Scott - Dancing On My Own (Official Video)
(Calum Scott)
4. A Color Test That Can Tell Your Mental Age
5. Coding Challenge 166: ASCII Text Images
(The Coding Train)
6. Which one did you think was the real one? 😂❤️ #shorts #artist #art #drawing #creative
(Yasmin Art Drawing)
Top Articles
Latest Posts
Article information

Author: Carmelo Roob

Last Updated: 12/02/2022

Views: 6091

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.