在尝试遵守python样式规则时,我将编辑器设置为最多79列.
在PEP中,它建议在括号,括号和括号内使用python隐含的延续.但是,当我达到col限制时处理字符串时,它会有点奇怪.
例如,尝试使用多行
mystr = """Why, hello there
wonderful stackoverflow people!"""
Run Code Online (Sandbox Code Playgroud)
将返回
"Why, hello there\nwonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)
这有效:
mystr = "Why, hello there \
wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)
因为它返回:
"Why, hello there wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)
但是,当语句缩进几个块时,这看起来很奇怪:
do stuff:
and more stuff:
and even some more stuff:
mystr = "Why, hello there \
wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)
如果您尝试缩进第二行:
do stuff:
and more stuff:
and even some more stuff:
mystr = "Why, hello there \
wonderful stackoverflow people!"
Run Code Online (Sandbox Code Playgroud)
你的字符串最终为:
"Why, hello there wonderful stackoverflow …Run Code Online (Sandbox Code Playgroud) 在我尝试学习TDD时,尝试学习单元测试并使用mock与python.慢慢地掌握它,但不确定我是否正确地这样做.预警:我正在坚持使用python 2.4,因为供应商API是预先编译的2.4 pyc文件,所以我使用模拟0.8.0和unittest(不是unittest2)
给出'mymodule.py'中的示例代码
import ldap
class MyCustomException(Exception):
pass
class MyClass:
def __init__(self, server, user, passwd):
self.ldap = ldap.initialize(server)
self.user = user
self.passwd = passwd
def connect(self):
try:
self.ldap.simple_bind_s(self.user, self.passwd)
except ldap.INVALID_CREDENTIALS:
# do some stuff
raise MyCustomException
Run Code Online (Sandbox Code Playgroud)
现在在我的测试用例文件'test_myclass.py'中,我想模拟ldap对象.ldap.initialize返回ldap.ldapobject.SimpleLDAPObject,所以我认为这是我必须嘲笑的方法.
import unittest
from ldap import INVALID_CREDENTIALS
from mock import patch, MagicMock
from mymodule import MyClass
class LDAPConnTests(unittest.TestCase):
@patch('ldap.initialize')
def setUp(self, mock_obj):
self.ldapserver = MyClass('myserver','myuser','mypass')
self.mocked_inst = mock_obj.return_value
def testRaisesMyCustomException(self):
self.mocked_inst.simple_bind_s = MagicMock()
# set our side effect to the ldap exception …Run Code Online (Sandbox Code Playgroud) 我正在为SaltStack编写一些etcd模块并遇到这个奇怪的问题,它以某种方式阻止我捕获异常,我对它是如何做到这一点感兴趣.它似乎特别以urllib3为中心.
一个小脚本(不是盐):
import etcd
c = etcd.Client('127.0.0.1', 4001)
print c.read('/test1', wait=True, timeout=2)
Run Code Online (Sandbox Code Playgroud)
当我们运行它时:
[root@alpha utils]# /tmp/etcd_watch.py
Traceback (most recent call last):
File "/tmp/etcd_watch.py", line 5, in <module>
print c.read('/test1', wait=True, timeout=2)
File "/usr/lib/python2.6/site-packages/etcd/client.py", line 481, in read
timeout=timeout)
File "/usr/lib/python2.6/site-packages/etcd/client.py", line 788, in api_execute
cause=e
etcd.EtcdConnectionFailed: Connection to etcd failed due to ReadTimeoutError("HTTPConnectionPool(host='127.0.0.1', port=4001): Read timed out.",)
Run Code Online (Sandbox Code Playgroud)
好的,让我们抓住那个bugger:
#!/usr/bin/python
import etcd
c = etcd.Client('127.0.0.1', 4001)
try:
print c.read('/test1', wait=True, timeout=2)
except etcd.EtcdConnectionFailed:
print 'connect failed'
Run Code Online (Sandbox Code Playgroud)
运行:
[root@alpha _modules]# /tmp/etcd_watch.py
connect …Run Code Online (Sandbox Code Playgroud) 无论如何,你可以在多个结构中使用相同的函数来满足接口吗?
例如:
package main
import "fmt"
type Animal interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
type Wolf struct {}
func (w Wolf) Speak() string {
return "HOWWWWWWWWL"
}
type Beagle struct {}
func (b Beagle) Speak() string {
return "HOWWWWWWWWL"
}
type Cat struct {}
func (c Cat) Speak() string {
return "Meow"
}
func main() {
var a Animal
a = Wolf{}
fmt.Println(a.Speak())
}
Run Code Online (Sandbox Code Playgroud)
因为Wolf和Beagle共享完全相同的功能,无论如何都要编写一次该函数,然后在两个结构之间共享它们以便它们都满足Animal?
我不确定这是如何有效的代码:
class Library
def initialize(games)
@games = games
end
def add_game(game)
games << game
end
def games()
@games
end
end
games = ['WoW','SC2','D3']
lib = Library.new(games)
puts lib.games
lib.add_game('Titan')
puts lib.games
Run Code Online (Sandbox Code Playgroud)
这将打印出来:
魔兽SC2 D3泰坦
我认为它应该打印出来
魔兽SC2 D3
add_game方法不使用实例变量.作为Ruby的新手,我不明白它是如何工作的.不应该是:
def add_games(game)
@games << game
end
Run Code Online (Sandbox Code Playgroud)
我正在从一个教程中读到这个,但是我无法找到关于<<如何专门使用实例变量的任何内容.当处理数组'追加到数组'时,我认为'<<'刚刚过载.这实际上是在做Singleton类吗?
所以,这是一个由两部分组成的问题 -
例如:
def _mydecorator(func):
def wrapped(someval, *args, **kwargs):
do_something(someval)
return func(*args, **kwargs)
return wrapped
@_mydecorator
def foo(thisval, thatval=None):
do_stuff()
Run Code Online (Sandbox Code Playgroud)
出现此问题的原因是,当使用 SaltStack 的运行程序模块时,您可以在模块内定义函数,并且可以通过“salt-run”命令调用这些函数。如果上面的示例是 Salt runner 模块调用“bar”,那么我可以运行:
salt-run bar.foo aval bval
Run Code Online (Sandbox Code Playgroud)
salt-run 导入模块并使用您在命令行上给出的参数调用该函数。模块中以 _ 开头的任何函数或类中的任何函数都会被忽略,并且无法通过 salt-run 运行。
所以,我想定义一个类似超时装饰器的东西来控制函数可以运行多长时间。
我意识到我可以做类似的事情:
@timeout(30)
def foo():
...
Run Code Online (Sandbox Code Playgroud)
但我想让这个值可配置,这样我就可以运行类似的东西:
salt-run bar.foo 30 aval bval
salt-run bar.foo 60 aval bval
Run Code Online (Sandbox Code Playgroud)
上面的装饰器可以工作,但感觉就像一个黑客,因为它改变了函数的签名,而用户不知道,除非他们查看装饰器。
我还有另一种情况,我想制作一个装饰器来在 Salt runner 中的函数执行之前处理“预检查”。然而,预检查需要来自它所装饰的函数的一条信息。这是一个例子:
def _precheck(func):
def wrapper(*args, **kwargs):
ok = False
if len(args) > 0:
ok = run_prechecks(args[0])
else:
ok = run_prechecks(kwargs['record_id'])
if …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用flask-rest-api作为一个简单的示例webservice的框架,SQLAlchemy作为ORM。一切正常,除非处理更新。
这是有问题的代码:
@blp.arguments(DogSchema)
@blp.response(DogSchema)
def put(self, data, dog_id):
"""Update existing dog"""
try:
dog = Dog.query.get(dog_id)
except Exception as e:
abort(404, message="Item not found - %s" % e)
# update the dog here
return dog
Run Code Online (Sandbox Code Playgroud)
当它执行时,data变量是一个瞬态狗模型对象。flask-rest-api 负责对 JSON 请求中的数据进行反序列化,查看您的 Marshmallow 模式并创建正确类型的 sqlalchemy 模型对象。
为了完整起见,这是我的模型和模式:
class Dog(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String, nullable=False)
@api.definition("Dog")
class DogSchema(ma.ModelSchema):
class Meta:
model = Dog
strict = True
ordered = True
id = field_for(Dog, 'id', dump_only=True)
Run Code Online (Sandbox Code Playgroud)
我想要做的只是获取瞬态对象并使用所有属性更新会话中的对象。
我已经能够以两种不同的方式做到这一点,我都不喜欢这两种方式,我希望有更好的方法来做到这一点。
@blp.arguments(DogSchema)
@blp.response(DogSchema) …Run Code Online (Sandbox Code Playgroud) python ×4
coding-style ×1
decorator ×1
exception ×1
flask ×1
go ×1
marshmallow ×1
mocking ×1
ruby ×1
sqlalchemy ×1
unit-testing ×1