networkx icon indicating copy to clipboard operation
networkx copied to clipboard

use plain inheritance instead of class variables

Open danieleades opened this issue 3 years ago • 6 comments
trafficstars

use plain inheritance instead of class variables for Graph factory methods.

from discussion in #4014 it seems these factory methods were implemented as class methods for performance reasons, that no longer hold.

Using plain methods and inheritance instead of patching class methods is far less 'magic', and therefore easier to reason about. It uses plain old python inheritance instead.

there's another benefit too- if this library starts using type annotations, then an IDE or linter will ensure that consumers correctly subclass these factory methods, including enforcing return types that implement the Mapping protocol ("dict-like"). The use of class methods in the previous implementation confounds this static analysis

eg.

from collections.abc import Mapping

...

    def node_dict_factory(self) -> Mapping[X, Y]:
        """Factory function to be used to create the dict containing node attributes, keyed by node id."""
        return {}

where X is the node id type, and Y is the node attribute type

danieleades avatar Jul 23 '22 11:07 danieleades

FYI @NeilGirdhar

danieleades avatar Jul 23 '22 11:07 danieleades

I love this and hope the networkx team will as well.

enforcing return types that subclass dict

FYI I think this (and the various comments in the code) should say Mapping instead of dict. The phrase "dict-like object" should probably be "mapping" or collections.abc.Mapping.

NeilGirdhar avatar Jul 23 '22 18:07 NeilGirdhar

FYI I think this (and the various comments in the code) should say Mapping instead of dict. The phrase "dict-like object" should probably be "mapping" or collections.abc.Mapping.

Yeah I imagine that's probably the case

Edit: updated summary

danieleades avatar Jul 23 '22 19:07 danieleades

@MridulS this has been open for coming up on on 7 months now. How can I progress this?

@jarrodmillman, @dschult ?

danieleades avatar Jan 08 '23 13:01 danieleades

@MridulS this has been open for coming up on on 7 months now. How can I progress this?

@jarrodmillman, @dschult ?

ping maintainers?

danieleades avatar Dec 01 '23 22:12 danieleades

ping @rossbar

danieleades avatar Mar 10 '24 12:03 danieleades