pyiron_snippets - 短小、无依赖的Python片段。
项目描述
pyiron_snippets
这是我们pyiron项目认为普遍有用的独立Python片段的集合。
要符合包含条件,片段必须不依赖于Python标准库之外的任何内容,并且应该合理地放入单个文件中。
(注意,tests可能具有非标准依赖项,例如,为了确保片段在各种我们关心的边缘情况下都能正常工作,但实际的片段本身必须能够在干净的环境中良好运行。)
摘要
片段可能有更多的功能 - 查看测试套件是了解其功能的最佳方式 - 但这些示例将给出事情的大致情况。
颜色
只是到seaborn.color_palette()
的十六进制颜色的快捷方式
>>> from pyiron_snippets.colors import SeabornColors
>>> SeabornColors.white
'#ffffff'
弃用
轻松指示某些功能正在被弃用
>>> from pyiron_snippets.deprecate import deprecate
>>>
>>> @deprecate(message="Use `bar(a, b)` instead", version="0.5.0")
... def foo(a, b):
... pass
>>>
>>> foo(1, 2)
引发警告,如DeprecationWarning: __main__.foo is deprecated: Use bar(a, b) instead. It is not guaranteed to be in service in vers. 0.5.0 foo(1, 2)
DotDict
允许点访问的字典。有.items()
等。
>>> from pyiron_snippets.dotdict import DotDict
>>>
>>> d = DotDict({"a": 1})
>>> d.b = 2
>>> print(d.a, d.b)
1 2
Factory
制作仍然是可pickle的动态类
>>> from abc import ABC
>>> import pickle
>>>
>>> from pyiron_snippets.factory import classfactory
>>>
>>> class HasN(ABC):
... '''Some class I want to make dynamically subclass.'''
... def __init_subclass__(cls, /, n=0, s="foo", **kwargs):
... super(HasN, cls).__init_subclass__(**kwargs)
... cls.n = n
... cls.s = s
...
... def __init__(self, x, y=0):
... self.x = x
... self.y = y
>>>
>>> @classfactory
... def has_n_factory(n, s="wrapped_function", /):
... return (
... f"{HasN.__name__}{n}{s}", # New class name
... (HasN, ), # Base class(es)
... {}, # Class attributes dictionary
... {"n": n, "s": s}
... # dict of `builtins.type` kwargs (passed to `__init_subclass__`)
... )
>>>
>>> Has2 = has_n_factory(2, "my_dynamic_class")
>>>
>>> foo = Has2(42, y=-1)
>>> print(foo.n, foo.s, foo.x, foo.y)
2 my_dynamic_class 42 -1
>>> reloaded = pickle.loads(pickle.dumps(foo)) # doctest: +SKIP
>>> print(reloaded.n, reloaded.s, reloaded.x, reloaded.y) # doctest: +SKIP
2 my_dynamic_class 42 -1 # doctest: +SKIP
(Pickle与文档测试不太兼容 —— 你也无法运行pickle.dumps(pickle.loads(5))
!)
文件
文件系统操作快捷方式
>>> from pyiron_snippets.files import DirectoryObject, FileObject
>>>
>>> d = DirectoryObject("some_dir")
>>> d.write(file_name="my_filename.txt", content="Some content")
>>> f = FileObject("my_filename.txt", directory=d)
>>> f.is_file()
True
>>> f2 = f.copy("new_filename.txt", directory=d.create_subdirectory("sub"))
>>> f2.read()
'Some content'
>>> d.file_exists("sub/new_filename.txt")
True
>>> d.delete()
有后置操作
一个元类,引入了一个__post__
双下划线,它在MRO中所有对象的__init__
之后运行。
>>> from pyiron_snippets.has_post import HasPost
>>>
>>> class Foo(metaclass=HasPost):
... def __init__(self, x=0):
... self.x = x
... print(f"Foo.__init__: x = {self.x}")
>>>
>>> class Bar(Foo):
... def __init__(self, x=0, post_extra=2):
... super().__init__(x)
... self.x += 1
... print(f"Bar.__init__: x = {self.x}")
...
... def __post__(self, *args, post_extra=2, **kwargs):
... self.x += post_extra
... print(f"Bar.__post__: x = {self.x}")
>>>
>>> Bar().x
Foo.__init__: x = 0
Bar.__init__: x = 1
Bar.__post__: x = 3
3
老实说,考虑一下是否有其他解决问题的方法;这是一种黑暗魔法。
导入警报
当缺少可选依赖项时,对于(可选)功能优雅地失败。
>>> from pyiron_snippets.import_alarm import ImportAlarm
>>>
>>> with ImportAlarm(
... "Some functionality unavailable: `magic` dependency missing"
... ) as my_magic_alarm:
... import magic
>>>
>>> with ImportAlarm("This warning won't show up") as datetime_alarm:
... import datetime
>>>
>>> class Foo:
... @my_magic_alarm
... @datetime_alarm
... def __init__(self, x):
... self.x = x
...
... @property
... def magical(self):
... return magic.method(self.x)
...
... def a_space_odyssey(self):
... print(datetime.date(2001, 1, 1))
>>>
>>> foo = Foo(0)
>>> # Raises a warning re `magic` (since that does not exist)
>>> # but not re `datetime` (since it does and we certainly have it)
>>> foo.a_space_odyssey()
2001-01-01
>>> try:
... foo.magical(0)
... except NameError as e:
... print("ERROR:", e)
ERROR: name 'magic' is not defined
日志记录器
配置日志记录器,并写入pyiron.log
重试
如果你第一次没有成功
>>> from time import time
>>>
>>> from pyiron_snippets.retry import retry
>>>
>>> def at_most_three_seconds():
... t = int(time())
... if t % 3 != 0:
... raise ValueError("Not yet!")
... return t
>>>
>>> retry(at_most_three_seconds, msg="Tried and failed...", error=ValueError) % 3
0
根据调用时的系统时钟,这个简单的示例可能会给出如UserWarning: 尝试失败... 1.0秒后重试。至今已尝试1次...
之类的警告,最多两次。
单例
单例模式的元类。
>>> from pyiron_snippets.singleton import Singleton
>>>
>>> class Foo(metaclass=Singleton):
... pass
>>>
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。