0

I'm trying to find out what exactly the asterisk(*) means on the SQLAlchemy query below. Could anyone clarify please?

import uuid
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import or_
from sqlalchemy_utils.types.uuid import UUIDType

class House(Base):
    id = Column(Integer, primary_key=True)
    street = Column(UUIDType, default=uuid.uuid4, nullable=False, unique=True)
    zip_code = Column(UUIDType, index=True)

# Shell session
$: [...]
query = request.dbsession.query(House)
query = query.filter(or_(*[(getattr(Building, k) == getattr(self, k))
                          for k in ('street', 'zip_code')
                          if getattr(self, k) is not None]))
Heron Rossi
  • 681
  • 6
  • 18
  • https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists – Stan Zeez May 09 '18 at 19:41
  • See this tutorial about or_: http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.or_ – Stan Zeez May 09 '18 at 19:44
  • @StanZeez Ah, so its passing a `list` of clauses to the `or_()` function, right? `or_(instance1.street==instance2.stree, instance1.zip_code==instance2.zip_code)`. I get it now. Thanks! – Heron Rossi May 09 '18 at 20:01
  • It doesn't mean anything special in SQLAlchemy. It's just an unpacking of the list comprehension that follows it into the arguments of `or_(...)`, which takes one argument for each operand being or'd. – Iguananaut May 09 '18 at 20:05

1 Answers1

2

or_: produce a conjunction of expressions joined by OR SQL operator.

"*" means that the list produced in epression:

[(getattr(Building, k) == getattr(self, k)) for k in ('street', 'zip_code') if getattr(self, k) is not None]

will be wrapped up in a tuple before pass in or_.

Simple example (foo can get the variable number of arguments):

def foo(*args):
    print(type(args))
    for a in args:
        print(a)

foo(*[a for a in [1, 2, 3, 4, 5] if a % 2 == 0])
<type 'tuple'>
2
4
Stan Zeez
  • 1,138
  • 2
  • 16
  • 38