Skip to content

Small dispatching refactor: simple __call__ when no backends - #7761

Merged
rossbar merged 10 commits into
networkx:mainfrom
eriknw:call_no_backends
Jan 19, 2025
Merged

rossbar merged 10 commits into
networkx:mainfrom
eriknw:call_no_backends

Conversation

@eriknw

@eriknw eriknw commented Dec 9, 2024

Copy link
Copy Markdown
Contributor

Having a simple, short __call__ function when no backends are installed may make for nicer tracebacks and debugging.

I decided to define the __call__ functions outside the class, since this let us remove an indentation level instead of adding an indentation level.

Having a simple, short `__call__` function when no backends are installed
may make for nicer tracebacks and debugging.
@eriknw eriknw added the Dispatching Related to dispatching and backend support label Dec 9, 2024
@eriknw

eriknw commented Jan 3, 2025

Copy link
Copy Markdown
Contributor Author

Based on the conversation in #7776 (comment), I moved the call methods back to the class body. In particular, this makes the diff much smaller and, hence, easier to review (and much less likely to cause annoying merge conflicts). It's probably where these methods belong anyway.

@Schefflera-Arboricola Schefflera-Arboricola left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @eriknw !

Left some suggestions and questions below. LMKWYT :)

Comment thread networkx/utils/backends.py Resolved
Comment thread networkx/utils/backends.py Resolved
def _call_no_backends_installed(self, /, *args, backend=None, **kwargs):
"""Returns the result of the original function (no backends installed)."""
if backend is not None and backend != "networkx":
raise ImportError(f"'{backend}' backend is not installed")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be more accurate to use ModuleNotFoundError here, but, ModuleNotFoundError is a subclass of ImportError, so we can also leave it like this also.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a great distinction to know and I think some people (including myself) often forget it. It's generally recommended to use ModuleNotFoundError around try: import ... except blocks for example. There can be other import errors that can prevent a module from being loaded, which is why I think ImportError was chosen here and elsewhere.

That said, I think I'd be okay with changing these to ModuleNotFoundError, but I don't have a strong opinion either way. If desired, we can also change these in a new PR, since this PR doesn't actually introduce raising these errors.

)

# Do dispatching (or not) when called depending on whether backends are installed
__call__: typing.Callable = (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does defining __call__ as an attribute instead of a method results in any major performance(or any other kinds of) advantages? If yes, then should we convert any other methods of the _dispatchable class also into attributes?

Also, now because __call__ is an attribute, a user can do something like :

>>> import networkx as nx
>>> nx.utils.backends._dispatchable.__call__ = nx.utils.backends._dispatchable._call_no_backends_installed # or put any function here
>>> G = nx.erdos_renyi_graph(10, 0.5)
>>> nx.betweenness_centrality(G, backend="parallel")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/workspaces/networkx/networkx/utils/decorators.py", line 788, in func
    return argmap._lazy_compile(__wrapper)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<class 'networkx.utils.decorators.argmap'> compilation 18", line 4, in argmap_betweenness_centrality_14
  File "/workspaces/networkx/networkx/utils/backends.py", line 964, in _call_no_backends_installed
    raise ImportError(f"'{backend}' backend is not installed")
ImportError: 'parallel' backend is not installed
>>> from importlib.metadata import entry_points
>>> entry_points(group="networkx.backends")
(EntryPoint(name='nx_loopback', value='networkx.classes.tests.dispatch_interface:backend_interface', group='networkx.backends'), EntryPoint(name='parallel', value='nx_parallel.interface:BackendInterface', group='networkx.backends'))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that assigning __call__ to a function object effectively enforces that it is set at class definition time rather than when the call is made. So the class definition changes based on the environment. I'm not sure of the advantages of this approach over something like:

    if backends:
        def __call__(...):
            <code when backends are present>
    else:
        def __call__(...):
            <code when backends not present>

Are there any side effects of assigning to __call__ that differ from the side-effects of defining __call__ inside an if structure?

@eriknw eriknw Jan 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks both for looking! Sorry for my slow replies (winter delays...).

To clarify, __call__ is a class method both before and after these changes. It's in the class __dict__, not the instance dict, so it's not an instance attribute. There is no performance penalty between assigning a method via def f vs f = ....

Examples:

In [2]: class A:
   ...:     def f(self, x):
   ...:         return x
   ...:     g = f
   ...:

In [3]: A.f
Out[3]: <function __main__.A.f(self, x)>

In [4]: A.g
Out[4]: <function __main__.A.f(self, x)>

In [5]: A.__dict__
Out[5]:
mappingproxy({'__module__': '__main__',
              'f': <function __main__.A.f(self, x)>,
              'g': <function __main__.A.f(self, x)>,
              '__dict__': <attribute '__dict__' of 'A' objects>,
              '__weakref__': <attribute '__weakref__' of 'A' objects>,
              '__doc__': None})

In [6]: A().__dict__
Out[6]: {}

In [7]: a = A()

In [8]: %timeit a.f
47.9 ns ± 0.256 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)  
In [9]: %timeit a.g
48 ns ± 0.631 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) 

The advantages of defining two different functions then assigning __call__ to one of them are:

  • One less indentation
  • Both functions are available (to use or introspect)
    • When testing with nx-loopback, we update __call__ to use _call_backends_installed
      • Hmm, I should verify that this doesn't do anything wonky with argmap...
        • edit: works as expected; argmap doesn't seem to do anything untoward

Are there any side effects of assigning to call that differ from the side-effects of defining call inside an if structure?

With if: def __call__, only one function is ever defined. With __call__ =, __call__.__name__ will be e.g. "_call_backends_installed" (but we can change the name).

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me.
I think it selects the call function at class definition time based on whether there are backends installed or not.
I can believe this helps shorten the traceback on exceptions, but I did not explore that. (And thanks @eriknw for working to shorten them!)

I'm guessing that the typing.Callable type annotation is useful somehow, but it made that harder for me to understand. Can we take out the annotation? Or does it serve a purpose beyond indicating that call is callable?

What do you think of using an if structure to define __call__ differently based on backends? This should be fine as is, but I'm trying to learn more. I'm guessing the set-an-attribute way leaves the two original methods there, while if only defines one method. And the indent level is more with the if structure.

I approve this PR even as I try to learn about it. :}

I actually like the version with the methods/functions defined outside of the class. For me it separated the call logic from the rest of the class, but I'm good either way.

)

# Do dispatching (or not) when called depending on whether backends are installed
__call__: typing.Callable = (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that assigning __call__ to a function object effectively enforces that it is set at class definition time rather than when the call is made. So the class definition changes based on the environment. I'm not sure of the advantages of this approach over something like:

    if backends:
        def __call__(...):
            <code when backends are present>
    else:
        def __call__(...):
            <code when backends not present>

Are there any side effects of assigning to __call__ that differ from the side-effects of defining __call__ inside an if structure?

@eriknw

eriknw commented Jan 16, 2025 •

Copy link
Copy Markdown
Contributor Author

I can believe this helps shorten the traceback on exceptions, but I did not explore that. (And thanks @eriknw for working to shorten them!)

Yup, that's the idea! Cleaner "pure networkx" experience.

edit: I just double checked, and this does indeed simplify the traceback

I'm guessing that the typing.Callable type annotation is useful somehow, but it made that harder for me to understand. Can we take out the annotation? Or does it serve a purpose beyond indicating that call is callable?

It was to make mypy happy. It's very very confused and unhappy otherwise.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for simpler tracebacks! Thanks @eriknw , @dschult and @Schefflera-Arboricola for the changes and review!

@rossbar
rossbar merged commit 75d1522 into networkx:main Jan 19, 2025
@jarrodmillman jarrodmillman added this to the 3.5 milestone May 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Dispatching Related to dispatching and backend support type: Maintenance

Development

Successfully merging this pull request may close these issues.

6 participants