티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

What is the right way to treat Python argparse.Namespace() as a dictionary?

Python의 argparse.Namespace()을 dictionary로 처리하는 올바른 방법은 무엇인가요?

 문제 내용 

If I want to use the results of argparse.ArgumentParser(), which is a Namespace object, with a method that expects a dictionary or mapping-like object (see collections.Mapping), what is the right way to do it?

argparse.ArgumentParser()의 결과인 Namespace 객체를, 사전이나 매핑과 유사한 객체를 받는 메서드에서 사용하려면 올바른 방법은 무엇인가요?
C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> args.baz = 'yippee'
>>> args['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Namespace' object has no attribute '__getitem__'
>>> dir(args)
['__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '_
_format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__
', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs', 'ba
r', 'baz', 'foo']

 

Is it proper to "reach into" an object and use its __dict__ property?

객체의 __dict__ 속성을 사용하여 객체에 접근하는 것은 올바른 방법인가요?

 

I would think the answer is no: __dict__ smells like a convention for implementation, but not for an interface, the way __getattribute__ or __setattr__ or __contains__ seem to be.

대답은 '아니오'라고 생각합니다. __dict__는 구현을 위한 관습같지만 __getattribute__, __setattr__ 또는 __contains__처럼 보이는 방식의 인터페이스는 아닙니다.

 

 

 

 높은 점수를 받은 Solution 

You can access the namespace's dictionary with vars():

vars()를 사용하여 네임스페이스의 딕셔너리에 액세스할 수 있습니다.
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

 

You can modify the dictionary directly if you wish:

원한다면, 딕셔너리를 직접 수정할 수 있습니다.
>>> d['baz'] = 'store me'
>>> args.baz
'store me'

 

Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.

네, __dict__ 속성에 접근하는 것은 괜찮습니다. 이것은 잘 정의되어 있으며, 테스트되었으며 보장된 동작입니다.

 

 

 

 가장 최근 달린 Solution 

Straight from the horse's mouth:

권위자의 직접적인 발언

 

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'} 

— The Python Standard Library, 16.4.4.6. The Namespace object

만약 객체의 속성을 dict와 같은 형태로 뷰(view)하길 원한다면, 표준 파이썬 관용구인 vars()를 사용할 수 있습니다: 

파이썬 표준 라이브러리, 16.4.4.6. The Namespace object

 

 

 

출처 : https://stackoverflow.com/questions/16878315/what-is-the-right-way-to-treat-python-argparse-namespace-as-a-dictionary

반응형
댓글
공지사항
최근에 올라온 글