Search code examples
pythondjangodjango-viewsurl-routing

Difference between reverse() and reverse_lazy() in Django


I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported (Ref: Reverse_lazy and URL Loading?)

What I don't understand is:

How are the urls loaded when we call reverse from the FBV? As when we import the views at the top of the urls.py in a Django app, urlpatterns list is yet to be evaluated. How does reverse() for FBV work but not for CBV?


Solution

  • #importme.py
    def a():
        print("FUNCTION HELLO")
    
    class B():
        print("CLASS HELLO") 
        
    
    >>> import importme
    >>> CLASS HELLO
    

    Edit: The reason: The class creation process involves executing the body of the class.

    The class body is executed (approximately) as exec(body, globals(), namespace). [...] Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds).

    https://docs.python.org/3/reference/datamodel.html?highlight=metaclass#executing-the-class-body



    My original answer text. You can ignore it - I'm just leaving it in because mirek's comment was a direct response to it:

    Class attributes are evaluated on import. The answer to when or exactly how that happens, resides within the depths of python's import system.