Goun2
Goun2

Reputation: 437

How to acess a global variable and change its value from another module

I have a global variable that is Increasing, and I wanna reset the counter from another module.

Whenever post_save signal runs, Counter variable increases and I see the number in the terminal.

But I will call a code from another module and I want to set counter to 0, So when I call post_save signal again it starts from 0.

As I did it seems there are 2 variables.

counter = 0
@receiver(post_save, sender=Numbers)
def num_post(sender, **kwargs):
    global counter
    counter += 1
    print(counter)
    dict = {}
    for object in Numbers.objects.all():
        dict[object.pk] = object.number
        print(dict)


    Group('group1').send({
        'text': json.dumps(dict)
    })

from .models import counter

    def ws_disconnect(message):
        global counter
        counter = 0
        print(counter)
        Group('eae').discard(message.reply_channel)
        Group('opa').discard(message.reply_channel)

Upvotes: 0

Views: 73

Answers (1)

Alex Hall
Alex Hall

Reputation: 36013

The attributes of a module object correspond to the globals inside that module. This is already familiar if you've ever said import module; module.function(). Well, you can set attributes in the same way.

from . import models
models.counter = 0

Upvotes: 1

Related Questions