def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
Run Code Online (Sandbox Code Playgroud)
在上面的代码块中,来自https://docs.python.org/3.5/tutorial/controlflow.html#documentation-strings
我的问题是关于-> str上面的代码块中的。它有什么作用 ?
在其他语言中,任何类似示例都会引发类型错误.为什么不用Python?
>>> def foo(a:int) -> str:
return a+1
>>> foo(5)
6
Run Code Online (Sandbox Code Playgroud) 我是新手,所以使用我在网上找到的一个例子来添加一些自定义日志记录级别。这将包含在一个库中,该库将被导入到各种脚本中。它按预期工作,但添加的级别未显示在自动完成列表中(使用 PyCharm),并且 PyCharm 抱怨 LOGGER 中存在未解析的属性引用。当我编码并输入“LOGGER”时。我看到正常的错误、警告、信息等可供选择,但我的自定义级别“详细”不在列表中。随着时间的推移,将会添加更多自定义级别,这也将推出给一个开发团队,所以我需要让这个工作。
知道为什么我的自动完成列表中没有详细选项吗?
这是我的文件。
px_logger.py
from logging import getLoggerClass, addLevelName, setLoggerClass, NOTSET
public class PxLogger(getLoggerClass()):
def __init__(self, name, level=NOTSET):
super(PxLogger, self).__init__(name, level)
addLevelName(5, "VERBOSE")
def verbose(self, msg, *args, **kwargs):
"""Custom logger level - verbose"""
if self.isEnabledFor(5):
self._log(5, msg, args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
my_script.py
import json
import logging.config
from px_logger import PxLogger
logging.setLoggerClass(PxLogger)
LOGGER = logging.getLogger(__name__)
with open('../logging.json') as f: # load logging config file
CONFIG_DICT = json.load(f)
logging.config.dictConfig(CONFIG_DICT)
LOGGER.verbose('Test verbose message')
Run Code Online (Sandbox Code Playgroud)
屏幕输出
VERBOSE - Test verbose message
Run Code Online (Sandbox Code Playgroud) 我在文档中读到 Python 3.5 版本中存在类型提示我在 ipython 终端中编写了两个函数来测试这对“相同”函数意味着什么。
def dostuff(name: str) -> str:
print(str.capitalize())
def do_stuff(name):
print(str.capitalize())
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,调用dostuff('arthur')并do_stuff('arthur')都返回 'Arthur'。
但是,调用do_stuff([])和dostuff([])都返回错误:
AttributeError: 'list' object has no attribute 'capitalize'
Run Code Online (Sandbox Code Playgroud)
这是有道理的,相同的错误在两者中都是有效的,但是为什么类型提示器/检查器实际上没有声明性地声明argument not of type 'str'或其他什么?
另外,如果您定义如下内容:
def do_stuff(name: str) -> str:
return list(name)
Run Code Online (Sandbox Code Playgroud)
即使函数应该返回一个字符串,解释器甚至不会抱怨我返回的是一个列表而不是一个字符串。
我知道这些都是人为的例子,但我做错了什么吗?
在 python 中,不需要指定方法参数类型。Python 动态地解释它们。
但是在一些代码片段中,我看到了正在定义的类型。
def method(p1: int, p2: int) -> None
Run Code Online (Sandbox Code Playgroud)
1) 为什么要这样做 2) 对于其他数据结构,我只需要定义数据结构而不是它接受的参数类型
def multiply(num1: list, num2: list):
Run Code Online (Sandbox Code Playgroud)
为什么这样设计的目的。
以及为什么我不能定义列表的类型
def multiply(num1: list[int], num2: list[int]):
Run Code Online (Sandbox Code Playgroud) 我找到了以下代码:
def get_iterator_from_config(config: dict, data: dict):
iterator_config = config['dataset_iterator']
iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config,data=data)
return iterator
Run Code Online (Sandbox Code Playgroud)
为什么迭代器有冒号然后有联合?这是否意味着迭代器的类型是联合?为什么不能只使用:
iterator= from_params(iterator_config,data=data)
Run Code Online (Sandbox Code Playgroud)