我在 SQLAlchemy 中有一堆要定义的表__repr__。
标准约定似乎是这样的:
def __repr__(self):
return "<TableName(id='%s')>" % self.id
Run Code Online (Sandbox Code Playgroud)
这对小桌子来说都很好。但是,我有 40 多列的表格。 有没有更好的构造方法,__repr__这样我就不用手动输入大量字符串?
我的包含所有表的文件称为models.py. 一种解决方案我想到了制作方法,_create_repr_string在models.py该负责自动生成的字符串进行__repr__返回。我想知道是否有更标准的方法来创建__repr__.
我为重复的代码片段启用了 PyCharm 检查(检查 --> 常规 --> 重复的代码片段)。
我正在尝试使用noinspection标签在我的 Python 代码中本地禁用此检查。但是,我无法弄清楚 noinspection 标签。它没有记录在我常用的来源中:pylover/inspections.txt
有人知道吗?
我尝试过的
不起作用的选项:
# noinspection Duplicates//noinspection Duplicates(这不适用于Python)# SuppressWarnings("Duplicates")# noinspection DuplicatedCode(来自JetBrains YouTrack PY-38309)我不想取消检查,我只是想能够局部抑制它。
我还尝试运行pylover/inspections.txt中记录的命令:
unzip -p lib/pycharm.jar com/jetbrains/python/PyBundle.properties | grep -B1 INSP.NAME | grep '^#' | sed 's|Inspection||g' | sed -e 's|#\s\{,1\}|# noinspection |'
Run Code Online (Sandbox Code Playgroud)
我在那里没有看到任何重复的内容。
版本
今天,我遇到了一个用 暗示的函数类型type。
我已经做了一些关于何时应该使用type或键入提示的研究Type,但我找不到满意的答案。根据我的研究,两者之间似乎存在一些重叠。
我的问题:
type和 和有什么区别Type?type显示何时使用vs 的示例用例是什么Type?研究
Type查看(from typingtag 3.7.4.3)的来源,我可以看到:
Run Code Online (Sandbox Code Playgroud)# Internal type variable used for Type[]. CT_co = TypeVar('CT_co', covariant=True, bound=type) # This is not a real generic class. Don't use outside annotations. class Type(Generic[CT_co], extra=type): """A special construct usable to annotate class objects. ```
它看起来Type可能只是 的别名type,但它支持Generic参数化。它是否正确?
例子
这是使用Python==3.8.5和制作的一些示例代码mypy==0.782:
from typing …Run Code Online (Sandbox Code Playgroud) 是否可以在不写实际数字的情况下制作 Markdown 编号列表?
例如,有时我有很长的编号列表(10 多个条目长)。如果我在第二个列表项之后插入一个项目,则必须随后更新所有项目编号。
更多详情
制作编号列表的众所周知的方法:
1. Foo
2. Bar
3. Baz
Run Code Online (Sandbox Code Playgroud)
我想要的是像下面这样的东西,并且让它像任何其他编号列表一样呈现。
#. Foo
#. Bar
#. Baz
Run Code Online (Sandbox Code Playgroud)
预先解决明显的解决方法
我知道从技术上讲,不必更新数字,并且它将使用顺序增加的编号列表自动呈现。
然而,这会导致源代码“混乱”(见下文),并且我不希望包含任何数字,但仍会得到一个编号列表。
1. Foo
9001. Spam
2. Bar
3. Baz
Run Code Online (Sandbox Code Playgroud) 我的任务本来应该很简单,但它却困扰了我一段时间。我正在尝试将patch一个对象导入到当前模块中。
根据Python 中模拟修补 from/import 语句的答案
我应该就可以了patch("__main__.imported_obj")。但是,这对我不起作用。请参阅我下面的最小重现(我正在通过以下方式运行测试pytest):
最小重现
这是使用 Python 3.8.6 运行的。
from random import random
from unittest.mock import patch
import pytest
@pytest.fixture
def foo():
with patch("__main__.random"):
return
def test(foo) -> None:
pass
Run Code Online (Sandbox Code Playgroud)
当我使用 PyCharm 运行此代码时,我得到一个AttributeError:
AttributeError: <module '__main__' from '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/_jb_pytest_runner.py'> does not have the attribute 'random'
Run Code Online (Sandbox Code Playgroud)
此外,当我在 之前的行中进入调试器模式时with patch,我看到该属性__main__未定义。我不确定是否需要定义它patch发挥其魔力。
注意:我知道我可以使用patch.object并且它变得更加容易。但是,我正在尝试弄清楚如何patch在这个问题中使用。
研究
这个问题是相关的,因为它是类似的错误消息和用例。他们的解决方案是使用builtins代替__main__,但那是因为他们尝试使用patch内置函数(open)。
我__name__对 Python 对象中的存储位置感到困惑。
以 Python 为例str:
In [1]: hasattr(str, "__name__")
Out[1]: True
In [2]: getattr(str, "__name__")
Out[2]: 'str'
In [3]: "__name__" in str.__dict__
Out[3]: False
In [4]: "__name__" in list(dir(str))
Out[4]: False
Run Code Online (Sandbox Code Playgroud)
您可以从[1]+ [2]that 中看到str.__name__,它具有值"str"。但是,我无法通过使用dir()和找到它的存储位置__dict__。
我知道我遗漏了一些东西,但从我所有的阅读中我无法弄清楚。你能帮我么?
看过的地方
从这些问题:
In [5]: str.__class__.__name__
Out[5]: 'type'
In [6]: "hi".__class__.__name__
Out[6]: 'str'
Run Code Online (Sandbox Code Playgroud)
可以看到一个str 实例已__name__ = "str" …
float我有一个基类,在方法的返回上有类型提示。
在子类中,在不重新定义签名的情况下,我可以以某种方式将方法返回的类型提示更新为 吗int?
示例代码
#!/usr/bin/env python3.6
class SomeClass:
"""This class's some_method will return float."""
RET_TYPE = float
def some_method(self, some_input: str) -> float:
return self.RET_TYPE(some_input)
class SomeChildClass(SomeClass):
"""This class's some_method will return int."""
RET_TYPE = int
if __name__ == "__main__":
ret: int = SomeChildClass().some_method("42"). #
ret2: float = SomeChildClass().some_method("42")
Run Code Online (Sandbox Code Playgroud)
我的 IDE 抱怨类型不匹配:
发生这种情况是因为我的 IDE 仍在使用SomeClass.some_method.
研究
我认为解决方案可能是使用泛型,但我不确定是否有更简单的方法。
建议也许使用实例变量注释,但我不确定如何对返回类型执行此操作。
我正在使用pytest的间接参数化来参数化上游设备。这对我来说一直很好。
但是,现在当上游设备具有相同的参数名称时,我被困住了,并且我想向它们传递不同的值。
当要参数化的上游设备的参数名称相同时,如何使用间接参数化?
示例代码
import pytest
class Config:
"""This is a configuration object."""
def __init__(self, a: int, b: int):
self._a = a
self._b = b
@pytest.fixture
def config(a: int, b: int) -> Config:
return Config(a, b)
class Foo:
def __init__(self, config: Config):
"""This does some behavior."""
self.config = config
@pytest.fixture
def foo(config: Config) -> Foo:
return Foo(config)
class Bar:
def __init__(self, config: Config):
"""This does some other behavior."""
self.config = config
@pytest.fixture
def bar(config: Config) -> Bar: …Run Code Online (Sandbox Code Playgroud) 请参阅下面的 Python 3.10 代码片段:
import contextlib
class Foo:
@contextlib.contextmanager
@classmethod
def state(cls):
try:
yield
finally:
pass
with Foo.state():
pass
Run Code Online (Sandbox Code Playgroud)
它抛出一个TypeError:
Traceback (most recent call last):
File "/path/to/code/play/quick_play.py", line 12, in <module>
with Foo.state():
File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 281, in helper
return _GeneratorContextManager(func, args, kwds)
File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 103, in __init__
self.gen = func(*args, **kwds)
TypeError: 'classmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
可以用classmethod来装饰吗contextlib.contextmanager?如果是的话,该怎么做?
我一直在互联网上阅读,以很好地解释 OPC-UA 中的节点。似乎有一些库可以用于它,但实际上没有一个解释节点。OPC-UA 中节点的用途是什么?
注意:此处为 OPC 和 OPC-UA 菜鸟
python ×8
pytest ×2
type-hinting ×2
attributes ×1
class-method ×1
generics ×1
markdown ×1
mocking ×1
node-opcua ×1
object ×1
oop ×1
opc-ua ×1
pycharm ×1
repr ×1
sqlalchemy ×1
unit-testing ×1