Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a class in python before it is declared

I am using direct examples from the Django REST framework tutorial, I have 2 classes: UserSerializer and SnippetSerializer. I want to be able to use UserSerializer as a serializer in the SnippetSerializer class declaration, but for reasons, SnippetSerializer needs to be declared first.

Code example:

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = UserSerializer()
    #unimportant stuff

class UserSerializer(serializers.HyperlinkedModelSerializer):
    #unimportant stuff - lets say we reference SnippetSerializer here

The obvious answer that comes to mind is a forward declaration, but from all my research, I cannot find this in Python.

Another solution I thought might work, which didn't (perhaps I did it wrong?) is instead trying to declare this relationship in the init method

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    def __init__(self, *args, **kwargs):
        self.owner = UserSerializer()
        super(SnippetSerializer, self).__init__(*args, **kwargs)

But this seemed to be completely ignored by the framework.

I also tried using the @addto, but it seems it only works for functions, not attributes/properties

Is there a way around this problem? This chicken-before-egg class problem has been killing me in Python for a while, but I've finally run into an instance where it is actually stopping me from getting the job done.

like image 286
Dakusan Avatar asked Apr 13 '26 03:04

Dakusan


1 Answers

You may be able to provide a string containing the (dot notation) path to the class, instead.

Using DRF, you may have a folder structure like so:

├── appname
│   ├── ...
│   └── serializers.py
├── ...

SnippetSerializer and UserSerializer declared inside the above serializers.py file.

You'd then reference UserSerializer using the string: "appname.serializers.UserSerializer" where you'd normally write UserSerializer

like image 76
Rik Schoonbeek Avatar answered Apr 14 '26 19:04

Rik Schoonbeek