JetBrains / awesome-pycharm

A curated list of resources for learning and using PyCharm, a Python IDE from JetBrains
Apache License 2.0
278 stars 45 forks source link

Class redefinition #14

Closed reob-info closed 3 years ago

reob-info commented 3 years ago

Initial Code:

class A:
    def __init__(self):
        self.x = 0

    @staticmethod
    def parse(json: str) -> A:
        print('Executed')
        return A()

a = A()
a.parse('')

Problem (when run in Python):

Traceback (most recent call last): File "c:\dev\test\python\t.py", line 1, in class A: File "c:\dev\test\python\t.py", line 6, in A
def parse(json: str) -> A: NameError: name 'A' is not defined

Solution:

class A:
    pass

class A:
    def __init__(self):
        self.x = 0

    @staticmethod
    def parse(json: str) -> A:
        print('Executed')
        return A()

a = A()
a.parse('')

This solution solves the problem in Python, but create many others in PyCharm.

Still I think that it is a problem with Python - that only include a class name in available classes after parses the entire code of the class, instead of when the line with the class definition was found - I think that PyCharm would suppor it.

Problem with this solution in PyCharm:

Appear the messages in problems saying:

Redeclared 'A' defined above without usage

And sometimes:

Unresolved attribute reference 'x' for class 'A'

And there are no way to remove these messages.

It occurs because PyCharm uses the stub defined, instead of the full class defined after, to find properties and methods for the class, and, because it, PyCharm will point that method 'parse' is not defined and property 'x' is an unresolved attribute reference.

PyCharm would take the last class definition instead of the first one (the stub) as reference to find their properties and methods.

pauleveritt commented 3 years ago

Hi, this repo is about collecting articles, and learning resources. Is this ticket about a support issue with PyCharm? If so, we can steer it to the correct spot.

reob-info commented 3 years ago

This ticket is about the errors reported by PyCharm, even when the code is correct and executes correctly.

This error should not be pointed, or at least would have a comment to disable them, like:

# noinspection PyMethodMayBeStatic

Because many errors are pointed, but they are not an error, they a solution to an error raised by Python, if they was not present.

reob-info commented 3 years ago

I found a solution to remove the warnings, still I continue thinking that what I pointed would be permited or maybe suggested to include the solution below.

from __future__ import annotations

Anyway, I would like to thanks for your answer.

pauleveritt commented 3 years ago

That's a good point about suggesting the forward references fix. I will relay to the team.