PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] How can I set the same type as class in method's parameter following PEP484?

 October 26, 2022     oop, pycharm, python, python-3.x, types     No comments   

Issue

My question is related with the new Python's type hints. I'm trying to add a type hint in an object's method who has a parameter of the same type of the object, but PyCharm are marking me as error (unresolved reference 'Foo'). The problem is as follows:

class Foo:

    def foo_method(self, other_foo: Foo):
        return "Hello World!"

So the question is how to define the type of other_foo parameter properly. Maybe __class__ is correct?


Solution

Inside of the class, the class is not defined yet, causing a NameError (and PyCharm to complain).

To get around this, use a forwarding reference:

class Foo:
    def foo_method(self, other_foo: "Foo"):
        return "Hello World!"

Basically, if a type annotations is a string, it is evaled when the type is requested (in the global scope rather than the scope of the class Foo), so it can evaluate to the Foo class.


You can also use the annotations feature, which will turn all annotations into strings:

from __future__ import annotations

class Foo:
    def foo_method(self, other_foo: Foo):
        return "Hello World!"

# Foo.foo_method.__annotations__ == {'other_foo': 'Foo'}
# typing.get_type_hints(Foo.foo_method) == {'other_foo': Foo}

This is available since 3.7, and was slated to become the default behaviour in 3.10 but was postponed.



Answered By - Artyer
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing