Python SQLAlchemy:逗号如何确定查询返回的是字符串还是元组?
在SQLAlchemy中,如果在查询中输入逗号(如下所示),则返回一个“字符串”。如果不加逗号,就得到一个元组。为什么会这样?我看不到文档中解释的任何地方 使用SQLAlchemy0.8 下面的代码返回一个字符串:Python SQLAlchemy:逗号如何确定查询返回的是字符串还是元组?,python,sqlalchemy,Python,Sqlalchemy,在SQLAlchemy中,如果在查询中输入逗号(如下所示),则返回一个“字符串”。如果不加逗号,就得到一个元组。为什么会这样?我看不到文档中解释的任何地方 使用SQLAlchemy0.8 下面的代码返回一个字符串: def get_password(self, member_id): for password, in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id):
def get_password(self, member_id):
for password, in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id):
return password
这将返回一个类“str”:“mypassword”
下面的代码返回一个元组
def get_password(self, member_id):
for password in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id):
return password
这将返回一个类'sqlalchemy.util.\u collections.KeyedTuple':('mypassword',)
这是因为查询始终返回一个元组,但逗号将该元组的元素分配给变量:
>>> foo, bar = (1, 2)
>>> foo
1
>>> bar
2
>>> baz, = (3, )
>>> baz
3
这也适用于for循环:
>>> for a, b in [(1, 'x'), (2, 'y')]:
... print a, "and b is", b
...
1 and b is x
2 and b is y
这称为“tuple unpacking”这是因为查询总是返回一个tuple,但逗号将该tuple的元素分配给变量:
>>> foo, bar = (1, 2)
>>> foo
1
>>> bar
2
>>> baz, = (3, )
>>> baz
3
这也适用于for循环:
>>> for a, b in [(1, 'x'), (2, 'y')]:
... print a, "and b is", b
...
1 and b is x
2 and b is y
这称为“元组解包”