1

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?

2
  • 3
    Because after the first replace call there's no 'https://api.' to replace. Commented Sep 7, 2014 at 23:09
  • @AshwiniChaudhary, ahhh! Didn't see that coming. Commented Sep 7, 2014 at 23:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool. But it's safe to say that even if the replace is fixed, sharing a global var could cause conflicts when there's more than one instance of the class, right?
Yes. If you want something for the instance, make it an attribute of self.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.