Views and objects


The NDB objects are dictionary-like structures that represent network objects – interfaces, routes, addresses etc. In addition to the usual dictionary API they have some NDB-specific methods, see the RTNL_Object class description below.

The dictionary fields represent RTNL messages fields and NLA names, and the objects are used as argument dictionaries to normal IPRoute methods like link() or route(). Thus everything described for the IPRoute methods is valid here as well.

See also: IPRoute module


# create a vlan interface with IPRoute
with IPRoute() as ipr:"add",

# same with NDB:
with NDB(log="stderr") as ndb:

Slightly simplifying, if a network object doesn’t exist, NDB will run an RTNL method with “add” argument, if exists – “set”, and to remove an object NDB will call the method with “del” argument.

Accessing objects

NDB objects are grouped into “views”:

  • interfaces

  • addresses

  • routes

  • neighbours

  • rules

  • netns

Views are dictionary-like objects that accept strings or dict selectors:

# access eth0

# access eth0 in the netns test01
ndb.interfaces[{"target": "test01", "ifname": "eth0"}]

# access a route to

# same with a dict selector
ndb.routes[{"dst": "", "dst_len": 24}]

Objects cache

NDB create objects on demand, it doesn’t create thousands of route objects for thousands of routes by default. The object is being created only when accessed for the first time, and stays in the cache as long as it has any not committed changes. To inspect cached objects, use views’ .cache:

>>> ndb.interfaces.cache.keys()
[(('target', u'localhost'), ('tflags', 0), ('index', 1)),  # lo
 (('target', u'localhost'), ('tflags', 0), ('index', 5))]  # eth3

There is no asynchronous cache invalidation, the cache is being cleaned up every time when an object is accessed.


class pyroute2.ndb.objects.RTNL_Object(view, key, iclass, ctxid=None, load=True, master=None, auth_managers=None)
set(key, value)

Set a field specified by key to value, and return self. The method is useful to write call chains like that:

 .set('mtu', 1200)
 .set('state', 'up')
 .set('address', '00:11:22:33:44:55')