我使用密封特性作为详尽模式匹配的枚举.如果我有case对象而不是扩展我的特性的case类,我想编码和解码(通过Circe)只是一个普通的字符串.
例如:
sealed trait State
case object On extends State
case object Off extends State
val a: State = State.Off
a.asJson.noSpaces // trying for "Off"
decode[State]("On") // should be State.On
Run Code Online (Sandbox Code Playgroud)
我知道这可以在0.5.0中配置,但任何人都可以帮我写一些东西来帮助我,直到它被释放?
我正在尝试编写一个使用其他上下文管理器的上下文管理器,因此客户端不需要知道整个配方,只需要知道我正在呈现的界面.我无法使用@contextmanager- yield如果您被异常中断,则调用后的代码不会被执行,因此我需要使用基于类的管理器.
这是一个小例子脚本:
from contextlib import contextmanager
import pprint
d = {}
@contextmanager
def simple(arg, val):
print "enter", arg
d[arg] = val
yield
print "exit", arg
del d[arg]
class compl(object):
def __init__(self, arg, val):
self.arg=arg
self.val=val
def __enter__(self):
with simple("one",1):
with simple("two",2):
print "enter complex", self.arg
d[self.arg] = self.val
def __exit__(self,*args):
print "exit complex", self.arg
del d[self.arg]
print "before"
print d
print ""
with compl("three",3):
print d
print ""
print "after"
print d
print ""
Run Code Online (Sandbox Code Playgroud)
这输出:
before …Run Code Online (Sandbox Code Playgroud) 今天早上我有一个有趣的问题.我有一个基类看起来像这样:
# base.py
class Base(object):
@classmethod
def exists(cls, **kwargs):
# do some work
pass
Run Code Online (Sandbox Code Playgroud)
还有一个看起来像这样的装饰模块:
# caching.py
# actual caching decorator
def cached(ttl):
# complicated
def cached_model(ttl=300):
def closure(model_class):
# ...
# eventually:
exists_decorator = cached(ttl=ttl)
model_class.exists = exists_decorator(model_class.exists))
return model_class
return closure
Run Code Online (Sandbox Code Playgroud)
这是我的子类模型:
@cached_model(ttl=300)
class Model(Base):
pass
Run Code Online (Sandbox Code Playgroud)
事实上,当我实际上调用Model.exists时,我得到关于错误数量的参数的抱怨!检查装饰器中的参数显示没有任何奇怪的事情 - 参数正是我所期望的,并且它们与方法签名匹配.如何将其他装饰器添加到已经装饰的方法中classmethod?
并非所有模型都被缓存,但exists()方法作为类方法存在于每个模型上,因此重新排序装饰器不是一个选项:cached_model可以将类方法添加到exists(),但是什么使exists()成为类方法在未缓存的模型?
我有一个像这样设置的结构任务:
@task
def cli():
command = [
os.path.join(env.servers_path, "bin", "redis-cli"),
]
run(" ".join(command))
Run Code Online (Sandbox Code Playgroud)
运行它会给我一个提示,但没有交互性:
$ fab cli
[server] Executing task 'cli'
[server] Executing task 'redis.cli'
[server] run: /path/to/bin/redis-cli
[server] out: redis 127.0.0.1:6379> help
<no output produced>
Run Code Online (Sandbox Code Playgroud)
键入进一步会产生一个“out:”提示,我在上面键入,但我从来没有从 redis 得到任何东西。
但是,如果我更改为其他一些交互式提示,我确实会获得交互性:
@task
def cli():
command = [
"python"
]
run(" ".join(command))
Run Code Online (Sandbox Code Playgroud)
产生:
$ fab cli
[server] Executing task 'cli'
[server] run: python
[server] out: Python 2.4.3 (#1, Sep 3 2009, 15:37:37)
[server] out: [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 …Run Code Online (Sandbox Code Playgroud)