복붙노트

[PYTHON] PyCharm에게 매개 변수의 유형을 알려주려면 어떻게해야합니까?

PYTHON

PyCharm에게 매개 변수의 유형을 알려주려면 어떻게해야합니까?

생성자와 할당, 메소드 호출에 관해서, PyCharm IDE는 내 소스 코드를 분석하고 각각의 변수가 어떤 타입인지 알아내는 것에 꽤 능숙합니다. 나는 좋은 코드 완성과 매개 변수 정보를 제공하기 때문에 그것이 맘에 든다. 존재하지 않는 속성에 접근하려고하면 경고 메시지를 보낸다.

그러나 매개 변수에 관해서는 아무 것도 모릅니다. 코드 완성 드롭 다운은 매개 변수의 유형을 알지 못하기 때문에 아무 것도 표시 할 수 없습니다. 코드 분석에서는 경고를 찾을 수 없습니다.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth()   # shows warning -- Person doesn't have a dig_filth method

class King:
    def repress(self, peasant):
        # PyCharm has no idea what type the "peasant" parameter should be
        peasant.knock_over()   # no warning even though knock_over doesn't exist

King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person

이것은 어느 정도 의미가 있습니다. 다른 호출 사이트는 해당 매개 변수를 전달할 수 있습니다. 그러나 만약 내 메소드가 매개 변수가 타입, 예를 들어 pygame.Surface라고 기대한다면, PyCharm에이를 나타낼 수 있기를 바란다. 그래서 코드 완성 드롭 다운에 Surface의 모든 속성을 보여줄 수있다. 잘못된 메서드를 호출하면 경고가 표시됩니다.

PyCharm에 힌트를 줄 수있는 방법이 있습니까, "psst,이 매개 변수는 X 유형이어야합니다"라고 말하고 있습니까? (또는 아마도 역동적 인 언어의 정신에서 "이 매개 변수는 X처럼 삐걱 거리는 소리가 들려오 는가?"나는 괜찮을 것이다.)

편집 : 아래의 CrazyCoder의 대답은 트릭을 않습니다. 빠른 요약을 원하는 나 같은 신규 사용자라면 여기 있습니다.

class King:
    def repress(self, peasant):
        """
        Exploit the workers by hanging on to outdated imperialist dogma which
        perpetuates the economic and social differences in our society.

        @type peasant: Person
        @param peasant: Person to repress.
        """
        peasant.knock_over()   # Shows a warning. And there was much rejoicing.

관련 부분은 @type peasant : 문서화 문자열의 Person 라인입니다.

File> Settings> Python Integrated Tools로 가서 "Docstring format"을 "Epytext"로 설정하면, PyCharm의 View> Quick Documentation Lookup은 모든 @line을 그대로 출력하지 않고 매개 변수 정보를 출력합니다.

해결법

  1. ==============================

    1.PyCharm이 유형을 알 수 있도록 메소드와 매개 변수에 대한 특수한 문서 형식을 사용할 수 있습니다. 최근 PyCharm 버전은 가장 일반적인 doc 형식을 지원합니다.

    PyCharm이 유형을 알 수 있도록 메소드와 매개 변수에 대한 특수한 문서 형식을 사용할 수 있습니다. 최근 PyCharm 버전은 가장 일반적인 doc 형식을 지원합니다.

    예를 들어 PyCharm은 @param 스타일 주석에서 유형을 추출합니다.

    reStructuredText 및 docstring 규칙을 참조하십시오 (PEP 257).

    또 다른 옵션은 Python 3 주석입니다.

    자세한 내용과 샘플은 PyCharm 문서 섹션을 참조하십시오.

  2. ==============================

    2.Python 3.0 이상을 사용하는 경우 함수 및 매개 변수에 대한 주석을 사용할 수도 있습니다. PyCharm은 인수 또는 반환 값이 가질 것으로 예상되는 유형으로 이것을 해석합니다.

    Python 3.0 이상을 사용하는 경우 함수 및 매개 변수에 대한 주석을 사용할 수도 있습니다. PyCharm은 인수 또는 반환 값이 가질 것으로 예상되는 유형으로 이것을 해석합니다.

    class King:
        def repress(self, peasant: Person) -> bool:
            peasant.knock_over() # Shows a warning. And there was much rejoicing.
    
            return peasant.badly_hurt() # Lets say, its not known from here that this method will always return a bool
    

    때로는 비공개 (non-public) 메소드에 유용하며, docstring이 필요 없다. 추가 이점으로, 이러한 주석은 코드를 통해 액세스 할 수 있습니다.

    >>> King.repress.__annotations__
    {'peasant': <class '__main__.Person'>, 'return': <class 'bool'>}
    

    업데이트 : Python 3.5에서 허용 된 PEP 484부터 주석을 사용하여 인수 및 반환 유형을 지정하는 공식 규칙입니다.

  3. ==============================

    3.PyCharm은 @type pydoc 문자열에서 유형을 추출합니다. PyCharm docs here and here와 Epydoc docs를 보라. 그것은 PyCharm의 '레거시'섹션에 있으며 아마도 일부 기능이 부족할 것입니다.

    PyCharm은 @type pydoc 문자열에서 유형을 추출합니다. PyCharm docs here and here와 Epydoc docs를 보라. 그것은 PyCharm의 '레거시'섹션에 있으며 아마도 일부 기능이 부족할 것입니다.

    class King:
        def repress(self, peasant):
            """
            Exploit the workers by hanging on to outdated imperialist dogma which
            perpetuates the economic and social differences in our society.
    
            @type peasant: Person
            @param peasant: Person to repress.
            """
            peasant.knock_over()   # Shows a warning. And there was much rejoicing.
    

    관련 부분은 @type peasant : 문서화 문자열의 Person 라인입니다.

    저의 의도는 CrazyCoder 또는 원래의 질문자로부터 포인트를 훔치지 않는 것입니다. 방금 대답이 '대답'슬롯에 있어야한다고 생각했습니다.

  4. ==============================

    4.PyCharm Professional 2016.1 py2.6-2.7 코드를 작성하고 있는데 reStructuredText를 사용하여 유형을 더 succint 방식으로 표현할 수 있다는 것을 알았습니다.

    PyCharm Professional 2016.1 py2.6-2.7 코드를 작성하고 있는데 reStructuredText를 사용하여 유형을 더 succint 방식으로 표현할 수 있다는 것을 알았습니다.

    class Replicant(object):
        pass
    
    
    class Hunter(object):
        def retire(self, replicant):
            """ Retire the rogue or non-functional replicant.
            :param Replicant replicant: the replicant to retire.
            """
            replicant.knock_over()  # Shows a warning.
    

    참조 : https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html#legacy

  5. ==============================

    5.당신은 또한 유형을 주장 할 수 있고 Pycharm은 그것을 유추 할 것입니다 :

    당신은 또한 유형을 주장 할 수 있고 Pycharm은 그것을 유추 할 것입니다 :

    def my_function(an_int):
        assert isinstance(an_int, int)
        # Pycharm now knows that an_int is of type int
        pass
    
  6. from https://stackoverflow.com/questions/6318814/how-can-i-tell-pycharm-what-type-a-parameter-is-expected-to-be by cc-by-sa and MIT license