Skip to content

Code design: function arguments like db=default_db() are only evaluated at function definition time, not each time the function is called #1212

@schroederlab

Description

@schroederlab

Hi,

I'm developing an extension based on suite2p that registers densely imaged volumes also in z, not just x and y (Carsen helped me by developing some extra functionality for this project). So, I'm making heavy use of your code and am now adapting my extension to the newest version.

I realised yesterday that I was using some of your functions incorrectly, and was wondering whether this design was intentional? An example is parameters.convert_settings_orig:

def convert_settings_orig(settings_in, db=default_db(), settings=default_settings()):

I called it only defining settings_in, assuming that db and settings would always give me the default values as defined by default_db() and default_settings(). But that's not the case, as these functions are called only once at function definition time. So, the first time one calls convert_settings_orig, one gets the default values, for any subsequent call, then db and settings will be whatever the function returned during the last call. Here's an explanation by Github Copilot on that:

In Python, the default expression db=default_db() in convert_settings_orig is evaluated exactly once, at function definition time (module import), not each time the function is called.
So, when you call convert_settings_orig(settings_in) (passing only the first argument), the default db is always used, but it is not re-created per call. The same applies to settings=default_settings().
That means you’re reusing the same default dict object created at import time. If the function mutates db (it does, via set_db(db, settings_in)), then later calls will observe the mutated state from previous calls.

I realise that you never use this function without explicitly defining db and settings. So, if this behavior was your intention, sorry for bothering you. I just thought I bring it up, in case you weren't aware.

That said: great work developing the suite2p toolbox. The newest version looks like a great improvement! :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions