The Python Oracle

Global "connection"-like variables in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
01:10 Accepted answer (Score 5)
02:09 Answer 2 (Score 1)
02:45 Thank you

--

Full question
https://stackoverflow.com/questions/1420...

Question links:
https://gist.github.com/4476526

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #cloudfiles

#avk47



ACCEPTED ANSWER

Score 5


You should create a class (called something like CloudContainer) that includes all of those global variables as members, and rewrite it as (just as a start):

class CloudContainers(object):
    def __init__(self, username, key, originContainerName, targetContainerName):
        self.username = username
        self.key = key     
        self.originContainerName = originContainerName
        self.targetContainerName = targetContainerName

    def cloudConnect(self):
        print "Creating connection"
        self.connection = cloudfiles.get_connection(self.username,self.key,servicenet=True)
        print "-- [DONE]"
        print "Accessing containers"
        self.originContainer = connection.create_container(self.originContainerName)
        self.targetContainer = connection.create_container(self.targetContainerName)
        print "-- [DONE]"
        return

    def uploadImg(self, new_name):
        new_obj = self.targetContainer.create_object(new_name)
        new_obj.content_type = 'image/jpeg'
        new_obj.load_from_filename("up/"+new_name)

    def getImg(name):
        obj = self.originContainer.get_object(name)
        obj.save_to_filename("down/"+name)

Thus, any function that uses these global variables (like getImg and uploadImg above) would be included as a method of the class.




ANSWER 2

Score 1


Easier, yes, but it means that it's very hard to tell when and why those variables get changed. I think the best answer is the one you have given in your question - pass them around as an object. E.g:

def cloud_connect(origin_container_name, target_container_name):
    print "Creating connection"
    connection = cloudfiles.get_connection(username, key, servicenet=True)
    print "-- [DONE]"
    print "Accessing containers"
    origin_container = connection.create_container(origin_container_name)
    target_container = connection.create_container(target_container_name)
    print "-- [DONE]"
    return connection, origin_container, target_container

Then simply pass that tuple around.