Is there any best practice or guidelines for when to have "context" as the first parameter of a method

Now, clearly some methods must have a context, operator execute methods for example. But when writing a library of functions to be used by addons is there any thoughts or advice on best practice around when and when not, to use context as the first parameter.

An example will help:

def find_collection_for_object(context, item):
    collections = item.users_collection
    if len(collections) > 0:
        return collections[0]
    return context.scene.collection

def find_collection(context, collection_name):
    if collection_name in
    return None

The first function here finds and returns a collection for the given item.
It’s pretty dumb just returning the first in the list, if it does not find one it returns the current active collection from the context.

The second returns the collection associated with the given name and if one does not exist returns None.

From an API consistency perspective, passing the context to both of them makes sense, but the second function has no need of the context, so we are passing it for nothing. If there is some science todeciding which way to jump on this then I’d love to hear your thoughts, perhaps it is just personal taste?


If your function doesn’t need context, why would you use it as a parameter? regarding consistency, name and document your functions in such a way that whoever is using your function doesn’t expect context to be needed. IE) “find_collection_for_object” clearly needs a context because the “object” is right there in the name. “find_collection” doesn’t because it’s clearly looking for a collection within all available collections. Any developer using your functions in any kind of serious way likely has intellisense of some kind, so it’s all a moot point anyway.

1 Like