Function annotation "->" does not return a error in python

Viewed 48

I created a sample class called Book to test the annotation function "->" I have used the notation "-> int" in the function number_authors to check if I get an error when I return a string, for example. However, I do not get an error in that situation. For example, the following code executes without error (even with number_authors returning a string instead of an integer as indicated by the annotation):

class Document:
    def __init__(self, document_id, authors):
        self.document_id = document_id
        self.authors = authors
    
    def add_authors(self,authors):
        self.author += authors
    
    def __repr__(self):
        return str(self.document_id) + " " + self.authors;

class Book (Document):
    def __init__(self, document_id, authors, publisher,title):
        super().__init__(document_id,authors)
        self.publisher = publisher
        self.title = title

    def __repr__(self):
        return super().__repr__() + " " + self.publisher + " " + self.title;
    
    def number_authors(self) -> int:
        return "3"


doc1 = Book(1,"Israel Freitas","Dexa", "New Database")
print(doc1)
print(doc1.number_authors())

Is there a way to force the function number_authors to return an int variable?

1 Answers

having code as example-001.py :

def greeting(name: str) -> str:
    return 1000

print(greeting('pippo'))

output :

1000

from https://docs.python.org/3/library/typing.html :

NoteThe Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

Installing mypy as suggested by Chris_Rands :

$ mypy example-001.py 

example-001.py:20: error: Incompatible return value type (got "int", expected "str")
Found 1 error in 1 file (checked 1 source file)



Related