Gezim
Gezim

Reputation: 7328

Python global not updating in new object instance

I have a Python file with a global var and define a class:

ROOT = 'https://api.example.com/2.0/'

class Mail(object):
    def __init__(self, api_key):
        self.name = "FName"

        if api_key.find('-'):
            dc = api_key.split('-')[1]

        global ROOT
        print "initing root to: %s" % (ROOT,)
        ROOT = ROOT.replace('https://api.', 'https://'+dc+'.api.')
        print "initing after replace of ROOT: %s" % (ROOT,)

    def pprint(self):
        print 'POST to %s' % (ROOT,)

It seems that the ROOT global is not updated once it's set:

>>> import pyglob 
>>> mc = pyglob.Mail('dfadsfad-us1')
initing root to: https://api.example.com/2.0/
initing after replace of ROOT: https://us1.api.example.com/2.0/
>>> mc.pprint()
POST to https://us1.api.example.com/2.0/
>>> mc3 = pyglob.Mail('dfadsfad-us3')
initing root to: https://us1.api.example.com/2.0/
initing after replace of ROOT: https://us1.api.example.com/2.0/
>>> mc3.pprint()
POST to https://us1.api.example.com/2.0/
>>> mc.pprint()
POST to https://us1.api.example.com/2.0/

Can someone explain how this works and why it happens?

Upvotes: 1

Views: 70

Answers (1)

Mike Graham
Mike Graham

Reputation: 76783

After you've made ROOT = https://us1.api.example.com/2.0/, ROOT.replace('https://api.', 'https://'+dc+'.api.') doesn't do anything, since 'https://api.' is no longer in ROOT--you've replaced it.

This whole situation looks extremely messy and you probably want to refactor this not to rebind globals at all.

Upvotes: 1

Related Questions