Search code examples
pythonpython-2.7sunburnt

Alternative way to use getattr in python?


I am trying to call a object functions which also allows several different function to be called through same object :

for eg: sort(), facet(),exclude() are different functions with their arguments and sort_flag, facet_flag and exclude_flag as condition set to true or false

can be called as:

si = sunburnt.SolrInterface("url","schema.xml")
response = si.query(arg1).facet(arg2).sort(arg3).exclude(arg4)

There can be certaing cases when I dont need to call all of these functions at same time or may be I dont have all the arguments to call these functions or vice versa. In that situtation how can I call si.facet(args).sort(args) something like this:

if sort_flag:
  --append sort function to the query
if exclude_flag:
  -- append exclude function

There can be alternative to do that using getattr but its confusing to use it using arguments of function and at same time it may generate lot of if check statements (for 3 flags close to 3 factorial statements)


Solution

  • I'm not sure I understood you, but can't you do this?

    si = sunburnt.SolrInterface("url","schema.xml")
    query = si.query(arg1).facet(arg2)
    
    if sort_flag:
      query = query.sort(arg3)
    if exclude_flag:
      query = query.exclude(arg4)
    
    response = query.execute()