#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Posts
    266
    Rep Power
    13

    Importing variables into a class


    The problem I am having is I want to import a file which just contains variable constants and is not a class. After I import qa_variables how do I access the variables from within the Qa_config class? With a class I import then create an instance and I am done. But with the variables file which is not a class I have nothing in instantiate. Maybe I am going about this all wrong but I'm not sure.

    from qa_common import *
    from qa_variables import *

    class Qa_config(Qa_common):
    def __init__(self):
    self.common = Qa_common()
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    If you do

    from mymodule import *

    then you are copying all the variables into your current namespace. This is generally frowned apon, since it pollutes your namespace and if you then import another module that has variables/classes/whatever of the same name then they will be overwritten.

    It sounds to me that what you want to do is:
    import mymodule

    then you can refer to the variables in it with mymodule.variablename.

    Modules are not the same as classes, but are objects in their own right.

    Dave - The Developers' Coach

    P.S. please learn to use [ code ] tags when putting python code in your posts. Without them the formatting gets screwed up and it can become unintelligible.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    11
    Just to give an example if you need even more clearing up:
    Code:
    # module vars.py
    VERSION = "1.5"
    DATADIR = "/usr/local/share/myapp"
    USERCONF = "/etc/myapprc"
    Code:
    # module myapp.py
    from vars import VERSION, DATADIR, USERCONF
    
    print "MyApp Version: %s" % VERSION
    print "MyApp Shared Data: %s" % DATADIR
    print "MyApp Configuration: %s" % USERCONF

IMN logo majestic logo threadwatch logo seochat tools logo