Nice programing

파이썬에서 변수 이름을 어떻게 인쇄 할 수 있습니까?

nicepro 2020. 11. 22. 20:34
반응형

파이썬에서 변수 이름을 어떻게 인쇄 할 수 있습니까?


이 질문에 이미 답변이 있습니다.

choice2와 같은 이름의 변수가 있다고 가정합니다. 변수 이름에 어떻게 액세스 할 수 있습니까? 동등한 것

In [53]: namestr(choice)
Out[53]: 'choice'

사전을 만드는 데 사용합니다. 이 작업을 수행하는 좋은 방법이 있으며 그냥 놓치고 있습니다.

편집하다:

이렇게하는 이유는 그렇습니다. 런타임에 조정하거나 조정하지 않으려는 여러 매개 변수를 사용하여 프로그램을 호출하는 데이터 분석 작업을 실행하고 있습니다. 마지막 실행에서 사용한 매개 변수를 다음과 같은 형식의 .config 파일에서 읽었습니다.

filename
no_sig_resonance.dat

mass_peak
700

choice
1,2,3

값을 입력하라는 메시지가 표시되면 이전에 사용 된 값이 표시되고 빈 문자열 입력은 이전에 사용 된 값을 사용합니다.

내 질문은 이러한 값이 스캔 된 사전을 작성할 때 발생합니다. 매개 변수가 필요한 경우 get_param파일에 액세스하여 매개 변수를 찾습니다.

나는. config한 번 파일을 만들고 그로부터 사전을 생성합니다. 원래는 ... 더 이상 기억 나지 않는 이유로 피했습니다. 내 코드를 업데이트하기에 완벽한 상황!


주장한다면 여기 끔찍한 검사 기반 솔루션이 있습니다.

import inspect, re

def varname(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
    if m:
      return m.group(1)

if __name__ == '__main__':
  spam = 42
  print varname(spam)

나는 그것이 당신이 가진 문제를 재평가하고 다른 접근 방식을 찾도록 영감을주기를 바랍니다.


원래 질문에 답하려면 :

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

예:

>>> a = 'some var'
>>> namestr(a, globals())
['a']

으로 @rbright 이미 지적 밖으로 당신이 무엇을 그것을 할 아마 더 좋은 방법이 있습니다 않습니다.


파이썬에는 변수가없고 이름 만 있기 때문에 그렇게 할 수 없습니다.

예를 들면 :

> a = [1,2,3]
> b = a
> a is b
True

이 둘 중 어느 것이 이제 올바른 변수입니까? a사이에는 차이가 없습니다 b.

이전에도 비슷한 질문 이있었습니다 .


이렇게하려고한다면 뭔가 잘못하고 있다는 뜻입니다. dict대신 사용을 고려하십시오 .

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

산출:

Name: b val: 2

특정 솔루션에 대한 세부 정보를 요청하는 대신 직면 한 문제를 설명하는 것이 좋습니다. 더 나은 답을 얻을 수있을 것 같아요. 나는 당신이하려는 것이 무엇이든 할 수있는 더 나은 방법이 거의 확실하기 때문에 이것을 말한다. 이러한 방식으로 변수 이름에 액세스하는 것은 일반적으로 모든 언어의 문제를 해결하는 데 필요하지 않습니다.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.


Will something like this work for you?

>>> def namestr(**kwargs):
...     for k,v in kwargs.items():
...       print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2

And in your example:

>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}

For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!


With eager evaluation, variables essentially turn into their values any time you look at them (to paraphrase). That said, Python does have built-in namespaces. For example, locals() will return a dictionary mapping a function's variables' names to their values, and globals() does the same for a module. Thus:

for name, value in globals().items():
    if value is unknown_variable:
        ... do something with name

Note that you don't need to import anything to be able to access locals() and globals().

Also, if there are multiple aliases for a value, iterating through a namespace only finds the first one.

참고URL : https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python

반응형