Search code examples
pythonpython-2.7argumentsflickr

Passing key-value pairs as function parameters in Python


I am working with the Python Flickr API and have a problem defining a function (I am kind of new to Python).

I need to wrap the following api functionality into a function:

photos = flickr.photos_search(
    tags="foo",
    is_commons="True")

This returns a photo search for the tag "foo" from Flickr's Commons collection.

Now I want to replace the tag each time I search, so I wrap it in a function:

def search_photos(fl_tags):
    photos = flickr.photos_search(
        tags=fl_tags,
        is_commons="True")

search_photos("foo")

This works, the is_commons flag however, I need to occasionally replace altogether (not only the value, but also the key, since there seems to be a bug in Flickr's API that it always searches in the Commons collection no matter to which value you set the flag).

In this case I would like to replace it with a key-value combination license="9".

I don't know how to put that into the function parameters. If I provide a fl_license parameter and simply set that to license="9" when I call the function then this does not work (as I kind of expected).

def search_photos(fl_tags, fl_license):
    photos = flickr.photos_search(
        tags=fl_tags,
        fl_license)

search_photos("foo", license="9")    # --> SyntaxError: non-keyword arg after keyword arg

Is there any way to get this to work. How could I get the key-value pair through a function parameter?

Thanks!


Solution

  • You could try something like this:

    def search_photos(fl_tags, license_val=''):
        if not license_val:
            photos = flickr.photos_search(
                tags=fl_tags,
                is_commons="True")
        else:
            photos = flickr.photos_search(
                tags=fl_tags,
                license=license_val)
        return photos
    
    search_photos("foo") # gives you the same output as before
    search_photos("foo", "9") # gives you the search with license as 9
    

    The variable = '' sets that parameter to an empty string by default if no argument is given (empty strings evaluate to false, so if you don't pass in a second arg, the function will default to a commons search). Otherwise, it will put whatever the second argument is as the license_val= parameter.