简体   繁体   English

Python 类型提示大写和小写字符串?

[英]Python type hinting for upper vs lower-cased strings?

In Python, if I am creating a list of strings, I would type hint like this:在 Python 中,如果我正在创建一个字符串列表,我会输入如下提示:

from typing import List
list_of_strings : List[str] = []
list_of_strings.append('some string')
list_of_strings.append('some other string')

Is there some way to type hint the expected case of the strings?有什么方法可以输入提示字符串的预期大小写吗? That way, when I write a comparison operator to search for a specific string, for example, I don't accidentally search for the mixed or upper-cased version of a string I know will be lower-cased because all strings in list_of_strings should be lower-cased.这样,当我编写比较运算符来搜索特定字符串时,例如,我不会意外搜索我知道将是小写的字符串的混合或大写版本,因为 list_of_strings 中的所有字符串都应该是小写。 I realize I can just add comments and refer back to the list's declaration, but I was wondering if there was a more integrated way to do it.我意识到我可以添加评论并返回列表的声明,但我想知道是否有更集成的方法来做到这一点。

An alternate way to solve this problem would be to make a class which extends str and rejects any values which aren't in the proper case, and then type hint for that class.解决此问题的另一种方法是创建一个 class 扩展 str 并拒绝任何不正确大小写的值,然后为该 class 键入提示。 Is there any reason why this would be a bad idea aside from it being more of a pain to create than a simple string?除了创建比简单的字符串更痛苦之外,还有什么理由说明这是一个坏主意吗?

The reason I run into this problem, is that I create lists, dicts, and other structures to store data, then need to add to or search them for a particular key/value and not knowing the expected case creates problems where I add duplicate entries because a simple if 'example' in string_list doesn't find it.我遇到这个问题的原因是我创建了列表、字典和其他结构来存储数据,然后需要添加或搜索它们以查找特定的键/值,并且不知道预期的情况会在我添加重复条目时产生问题因为 string_list 中的一个简单if 'example' in string_list没有找到它。 And doing if 'example'.upper() in string_list is easy to forget and not very pretty.并且在if 'example'.upper() in string_list很容易忘记并且不是很漂亮。 Jumping back and forth between the declaration (if I wrote a comment there describing expected case) and where I'm coding distracts from my flow, it would be nice to have the information when I'm referencing that object later.在声明(如果我在那里写了描述预期情况的评论)和我正在编码的地方来回跳转会分散我的流程,当我稍后引用 object 时,如果有这些信息会很好。

You can in Python 3.10 using typing.TypeGuard .您可以在 Python 3.10 中使用typing.TypeGuard

from typing import TypeGuard


class LowerStr(str):
    '''a dummy subclass of str, not actually used at runtime'''


def is_lower_str(val: str) -> TypeGuard[LowerStr]:
    return val.islower()


l: list[LowerStr] = []


def append(lst: list[LowerStr], v: str):
    if not is_lower_str(v):
        raise TypeError('oh no')
    lst.append(v)

You could indeed enforce runtime safety using a subclass of str .您确实可以使用str的子类来强制执行运行时安全。 The disadvantage would mostly be performance.缺点主要是性能。 You would want to take care to not add an unnecessary __dict__ , by adding __slots__ = () to the class definition, from the top of my head.您需要注意不要添加不必要的__dict__ ,方法是从我的脑海中将__slots__ = ()添加到 class 定义中。

Either way, string literals are not going to be validated automatically, so it will cause some overhead, either by calling the typeguard, passing them to the constructor of the subtype, or using cast(LowerStr, 'myliteral') .无论哪种方式,字符串文字都不会被自动验证,因此它会导致一些开销,要么调用类型保护,将它们传递给子类型的构造函数,要么使用cast(LowerStr, 'myliteral')

No, I've been searching on the net for this but it doesn't exist.不,我一直在网上搜索这个,但它不存在。

The Python's typing module doesn't provide any hint for lowercase or uppercase str ings. Python 的typing模块不提供任何小写或大写str的提示。


[...] type hint the expected case of the strings [...] 类型提示字符串的预期大小写

Remember that a type is for example str , and in this case you should be talking about hint and not about type hint .请记住, type例如是str ,在这种情况下,您应该谈论hint而不是type hint


You can anyway create a custom class in this scope:无论如何,您都可以在此 scope 中创建自定义 class:

class UppercaseString(str): pass

The UppercaseString will inherit all the functionalities of the built-in class str (that's what happens when you specify : pass in class declaration). UppercaseString将继承内置 class str的所有功能(当您指定时会发生这种情况: pass class声明)。

You can anyway create an instance 's method that checks if the string is really uppercase, and otherwise raises an error.无论如何,您都可以创建一个instancemethod来检查字符串是否真的是大写,否则会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM