1

I encountered with some wierd behavior, when trying to pass object like query which has the following structure:

query = session.query(...).filter(...)

To foo(query), while:

def foo_add_filter(query):
    # adding some condition
    query = query.filter(....)

When I exit function query wasn't updated, this lead me to understand the query is not passed by reference and therefore can't be altered inside function without return value.

If this is the state, how can I pass this query object by ref, without modifying my foo function to return value: query

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
JavaSa
  • 5,813
  • 16
  • 71
  • 121
  • Most of the methods of [`Query`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query) produce new instances instead of mutating the existing one. The dead simple solution here is to just return the new query from the function and use that. Note that in Python you have names, bound to values. When you call the function both the name `query` in the calling scope and `query` argument in the function scope are bound to the same value (until you rebind/assign in the function). – Ilja Everilä Dec 04 '17 at 11:52
  • Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Ilja Everilä Dec 04 '17 at 11:53
  • You should also read https://nedbatchelder.com/text/names.html. – Ilja Everilä Dec 04 '17 at 11:58
  • 1
    Thanks, returning the value is the only way if I got you right – JavaSa Dec 04 '17 at 12:00
  • 1
    It depends on how and where `foo_add_filter()` is defined in relation to the name `query` etc., but returning is a clear and simple solution. This is pretty much the same situation as if you'd want to produce a new `str` or any other immutable object in a function. – Ilja Everilä Dec 04 '17 at 12:05

0 Answers0