首页 > 后端开发 > Python教程 > 像 Typescript 一样编写 Python 代码

像 Typescript 一样编写 Python 代码

王林
发布: 2024-08-01 20:18:11
原创
709 人浏览过

我想想读这篇文章的人都知道什么是 typescript。 Javascript 开发人员创建了 Typescript 来使 javascript 更加安全。类型安全使代码更具可读性,并且无需编写任何测试即可减少错误。 python 可以实现类型安全吗?.

为什么我们需要类型安全?

想象一下这个看似无辜的函数

def send_email(sender, receiver, message):
    ...
登录后复制

我故意隐藏了它的代码实现。您能猜出函数的用途是什么以及我们需要什么参数才能仅通过函数名称和参数来使用该函数吗?从它的函数名称我们知道它的功能是发送电子邮件。它的参数怎么样,我们应该输入什么才能使用这个函数?

首先猜测发件人是电子邮件的 str,收件人是电子邮件的 str,消息是电子邮件正文的 str。

send_email(sender="john@mail.com", receiver="doe@mail.com", message="Hello doe! How are you?")
登录后复制

最简单的猜测。但这不是唯一的猜测。

第二个猜测发送者是数据库上 user_id 的 int,接收者是数据库上 user_id 的 int,消息是电子邮件正文的 str。

john_user_id = 1
doe_user_id = 2
send_email(sender=1, receiver=2, message="Hello doe! How are you?")
登录后复制

想象一下在应用程序上工作。大多数应用程序使用一些数据库。用户通常用它的 id 来表示。

第三个猜测发送者是字典,接收者是字典,消息是字典。

john = {
    "id": 1,
    "username": "john",
    "email": "john@mail.com"
}
doe = {
    "id": 2,
    "username": "doe",
    "email": "doe@mail.com"
}
message = {
    "title": "Greeting my friend doe",
    "body": "Hello doe! How are you?"
}
send_email(sender=john, receiver=doe, message=message)
登录后复制

也许 send_email 需要的不仅仅是电子邮件和用户 ID。为了在每个参数上添加更多数据,它使用了一些字典结构。您注意到该消息不仅仅是字符串,也许还需要标题和正文。

第四次猜测发送者是 User 类,接收者是 User 类,消息是字典。

class User():

    def __init__(self, id, username, email):
        self.id = id
        self.username = username
        self.email = email

john = User(id=1, username="john", email="john@mail.com")
doe = User(id=2, username="doe", email="doe@mail.com")
message = {
    "title": "Greeting my friend doe",
    "body": "Hello doe! How are you?"
}
send_email(sender=john, receiver=doe, message=message)
登录后复制

也许send_email 与一些数据库orm 集成,如Django ORM 或Sqlalchemy。为了方便最终用户使用,直接使用ORM类。

那么哪一个是正确答案呢?其中之一可能是正确答案。也许正确答案可以是两个猜测的结合。就像发送者和接收者一样,它是 User 类(第四次猜测),但消息是 str(第一次猜测)。除非我们阅读它的代码实现,否则我们无法确定。如果您是最终用户,这就是浪费时间。作为使用此函数的最终用户,我们只需要函数做什么、需要什么参数以及函数输出是什么。

解决方案

文档字符串

Python 使用文档字符串内置了功能文档。这里是文档字符串示例。

def add(x, y):
    """Add two number

    Parameter:\n
    x -- int\n
    y -- int\n

    Return: int
    """
    return x + y

def send_email(sender, receiver, message):
    """Send email from sender to receiver

    Parameter:\n
    sender -- email sender, class User\n
    receiver -- email receiver, class User\n
    message -- body of the email, dictionary (ex: {"title": "some title", "body": "email body"}\n

    Return: None
    """
    ...
登录后复制

文档字符串的优点是它与编辑器兼容。在 vscode 中,当您将鼠标悬停在函数上时,它将显示文档字符串。 Python 中的大多数库都使用文档字符串来记录其功能。

Writing Python code like Typescript

文档字符串的问题是文档同步。如何确保文档字符串始终与代码实现同步。你无法正确地测试它。我从互联网上随机的人那里听说“拥有过时的文档比没有文档更糟糕”。

文档测试

顺便说一句,您可以使用 doctest 来测试文档字符串。 Doctest 通过在文档字符串上运行示例来测试您的文档字符串。 Doctest 已预安装在 python 中,因此您不需要外部依赖项。让我们看一下这个示例,创建名为 my_math.py 的新文件,然后放入此代码。

# my_math.py
def add(x, y):
    """Add two integer

    Parameter:\n
    x -- int\n
    y -- int\n

    Return: int
    >>> add(1, 2)
    3
    """
    return x + y


if __name__ == "__main__":
    import doctest

    doctest.testmod()

登录后复制

它的代码与 docstring example 相同,但我在代码的最后一行添加了 example 和 doctest 。为了测试文档字符串,只需运行文件 python my_math.py。如果没有输出,则意味着您的示例通过了测试。如果您想查看输出,请在详细模式下运行 python my_math.py -v,您将看到此输出。

Trying:
    add(1, 2)
Expecting:
    3
ok
1 items had no tests:
    __main__
1 items passed all tests:
   1 tests in __main__.add
1 tests in 2 items.
1 passed and 0 failed.
Test passed
登录后复制

如果您在代码示例中犯错,它将返回错误。

# my_math.py
def add(x, y):
    """Add two integer

    Parameter:\n
    x -- int\n
    y -- int\n

    Return: int
    >>> add(2, 2) # <-- I change it here
    3
    """
    return x + y


if __name__ == "__main__":
    import doctest

    doctest.testmod()

登录后复制

输出:

**********************************************************************
File "~/typescript-in-python/my_math.py", line 12, in __main__.add
Failed example:
    add(2, 2) # <-- I change it here
Expected:
    3
Got:
    4
**********************************************************************
1 items had failures:
   1 of   1 in __main__.add
***Test Failed*** 1 failures.
登录后复制

太棒了!现在我可以测试我的文档字符串了。但注意事项是:

  1. doctest 只检查示例它不检查注释函数参数和返回
  2. doctest需要运行代码像其他测试工具一样,以检查它是否正确 doctest需要运行代码示例。如果您的代码需要一些外部工具,例如数据库或 smtp 服务器(例如发送电子邮件),则很难使用 doctest 进行测试。

Python 打字

有时你不需要运行代码来检查代码是否正确。您只需要输入类型和输出类型。如何?考虑这个例子。

def add(x, y):
    """Add two integer

    Parameter:\n
    x -- int\n
    y -- int\n

    Return: int
    """
    return x + y

def sub(x, y):
    """Substract two integer

    Parameter:\n
    x -- int\n
    y -- int\n

    Return: int
    """
    return x - y

a = add(2, 1)
b = add(1, 1)
c = sub(a, b)
登录后复制

函数add返回一个int,函数sub需要两个int作为输入参数。如果我使用添加函数的两个返回值,然后将其放在子参数上,如上面的示例,它会出错吗?当然不是因为 sub 函数需要 int 并且你也输入了 int。

从 python 3.5 开始,python 内置了称为打字的类型。通过输入,您可以在函数上添加类型,如下例所示。

def add(x: int, y: int) -> int:
    """Add two integer"""
    return x + y

a = add(1, 2)
登录后复制

Instead put it on your docstring you put it on the function. Typing is supported on many editor. If you use vscode you can hover on variable and it will shown it's type.
Writing Python code like Typescript

Nice now our code will have a type safety. eeehhhh not realy. If I intentionally use function incorrectlly like this.

def add(x: int, y: int) -> int:
    """Add two integer"""
    return x + y

res = add(1, [])
print(res)
登录后复制

It will show error

Traceback (most recent call last):
  File "~/typescript-in-python/main.py", line 5, in <module>
    res = add(1, [])
          ^^^^^^^^^^
  File "~/typescript-in-python/main.py", line 3, in add
    return x + y
           ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'list'
登录后复制

But it doesn't show that you put incorrect type. Even worse if you use it like this.

def add(x: int, y: int) -> int:
    """Add two integer"""
    return x + y

res = add("hello", "world")
print(res)
登录后复制
登录后复制

It will succeed. It must be error because you put incorrect type.

helloworld
登录后复制

Why python typing doesn't have type checker by default??. Based on pep-3107 it said

Before launching into a discussion of the precise ins and outs of Python 3.0’s function annotations, let’s first talk broadly about what annotations are and are not:

  1. Function annotations, both for parameters and return values, are completely optional.
  2. Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time. By itself, Python does not attach any particular meaning or significance to annotations. Left to its own, Python simply makes these expressions available as described in Accessing Function Annotations below.

The only way that annotations take on meaning is when they are interpreted by third-party libraries. ...

So in python typing is like a decorator in typescript or java it doesn't mean anything. You need third party libraries todo type checking. Let's see some library for typechecking.

Python typing + type checker

Here are libraries for typechecking in python. For example we will typecheck this wrong.py file

def add(x: int, y: int) -> int:
    """Add two integer"""
    return x + y

res = add("hello", "world")
print(res)
登录后复制
登录后复制

1.mypy

The "OG" of python type checker. To install it just using pip pip install mypy. Now let's use mypy to typecheck this file. Run mypy wrong.py. It will shown type error which is nice.

wrong.py:5: error: Argument 1 to "add" has incompatible type "str"; expected "int"  [arg-type]
wrong.py:5: error: Argument 2 to "add" has incompatible type "str"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)
登录后复制

btw you can run mypy on entire project by using mypy ..

2.pyright

Another typechecker is pyright. It created by microsoft. It's same like mypy install through pip pip install pyright. Then run it pyright wrong.py. It will shown this error.

~/typescript-in-python/wrong.py
  ~/typescript-in-python/wrong.py:5:11 - error: Argument of type "Literal['hello']" cannot be assigned to parameter "x" of type "int" in function "add"
    "Literal['hello']" is incompatible with "int" (reportArgumentType)
  ~/typescript-in-python/wrong.py:5:20 - error: Argument of type "Literal['world']" cannot be assigned to parameter "y" of type "int" in function "add"
    "Literal['world']" is incompatible with "int" (reportArgumentType)
2 errors, 0 warnings, 0 informations
登录后复制

It said that it's more faster than mypy but I found that's not much diffrent. Maybe my code base it's to small. Also pyright implement more python standard than mypy you can see on https://microsoft.github.io/pyright/#/mypy-comparison. Personaly I prefer mypy than pyright because the error message were more readable.

3.pylyzer

Speaking of performance and speed another new python typechecker pylyzer. It's written in rust. You can install it through pip pip install pylyzer or through cargo (rust package manager) cargo install pylyzer --locked. Then run it pylyzer wrong.py. It will shown this error.

Start checking: wrong.py
Found 2 errors: wrong.py
Error[#2258]: File wrong.py, line 5, <module>.res

5 | res = add("hello", "world")
  :           -------
  :                 |- expected: Int
  :                 `- but found: {"hello"}

TypeError: the type of add::x (the 1st argument) is mismatched

Error[#2258]: File wrong.py, line 5, <module>.res

5 | res = add("hello", "world")
  :                    -------
  :                          |- expected: Int
  :                          `- but found: {"world"}

TypeError: the type of add::y (the 2nd argument) is mismatched
登录后复制

So far this is the most readable and beautiful error message. It's reminds me of rust compiler error. Speed, performance and most readable error message, I think I will choose to using pylyzer if the package already stable. The problem is at the time I write this blog, pylyzer still in beta. It can only typecheck your code base, it haven't support external depedencies.

Conclusion

Alright we successfully write python code like typescript (kinda). There is more way to using python typing module other than check simple type (str, int, bool etc). Maybe I will cover more advance type it in next blog. Maybe you guys have opinion about this, know better typechecker other then those 3, found other way to do typecheck in python or other. let me know on comment section below. As always Happy Coding.

以上是像 Typescript 一样编写 Python 代码的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板