Search code examples
pyramid

Is the Context predicate ever useful when using URLDispatch in Pyramid?


I'm trying to wrap my head around the usefulness of the "context" predicate in Pyramid 1.6+. when only using URLDispatch For example, I might have a view callable decorated like this:

@view_config(route_name="employee_edit", context=Employee)
...

And let's say I have a route defined like this, with a route factory defined:

config.add_route("employee_edit","/employee/edit/{id}", factory=Employee)

Ignoring permission issues for the moment, Pyramid would probably find the above view callable acceptable when the user browses to the employee_edit route. Fine.

But my question is: what value does "context=Employee" have on my @view_config in the above example?..I have seen this in people's code.

If I understand things, context= basically means "this view can only be used if the context object contains the same type as the object specified in context=". In other words, in the example above, don't invoke this view unless it contains an Employee object.

But how could the context not contain an Employee object? In other words, in my example above I'm assuming I can only have one view specifying one route and that one route is hard coded to emit an Employee object in the context... it's not as if the view could be used for other routes, could it?


Solution

  • It's relevant in mainly 2 scenarios:

    1. If the factory may return different types of contexts, then you may want to match on that.

    2. If your route is using use_global_views=True and your view does not have route_name=, then your view is only coupled to a context and not to the explicit route.

    Otherwise, as in your example, it's redundant assuming the factory always returns a context of that type.