Variable passing between modules.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Golawala, Moiz M (GE Infrastructure)

    #1

    Variable passing between modules.

    Hi All,

    I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg:

    in module1


    if __name__ == '__main__':
    someVar = 'hello'
    import module2


    in module 2

    # here I would like to use someVar
    print someVar


    Thanks,
    Moiz Golawala
    GE Infrastructure, Security
    Software Engineer
    Enterprise Solutions

    T 561 994 5972
    F 561 994 6572
    E moiz.golawala@g e.com
    www.gesecurity.com

    791 Park of Commerce Blvd., Suite 100
    Boca Raton, FL, 33487, U.S.A.
    GE Security, Inc.

  • Jeff Shannon

    #2
    Re: Variable passing between modules.

    Golawala, Moiz M (GE Infrastructure) wrote:
    [color=blue]
    >Hi All,
    >
    >I want to pass a value between 2 modules. Both the modules are scripts (no classes involved). Does anyone know how I can do that. For eg:
    >
    >in module1
    >
    >
    >if __name__ == '__main__':
    > someVar = 'hello'
    > import module2
    >
    >
    >in module 2
    >
    ># here I would like to use someVar
    >print someVar
    >
    >
    >[/color]


    The best way to do this is to put your module2 code inside a function,
    and simply call that function with someVar as an argument.

    --- module2.py -----

    def go(somevar):
    print somevar

    --- module1.py -----
    import module2
    somevar = "hello"
    module2.go(some var)

    It *is* possible to insert a variable into another module's namespace,
    like so:

    import module2
    module2.somevar = somevar

    However, this won't accomplish what you want, because all of the code in
    module2 is executed when you import module2. If that code is all def
    statements, then you've created a bunch of functions that can be used
    later; however, if that code is all module-level imperative code, as you
    seem to be showing in your example, then it's all been executed by the
    time that module1 returns from the import statement. Inserting a
    variable into module2's namespace *will* let you use that variable as a
    global in any function in module2, but this has all of the drawbacks
    that globals always have plus a few more (tight coupling with module1,
    the potential to mistakenly think that rebinding module2.somevar will
    also rebind module1.somevar , etc)...

    Jeff Shannon
    Technician/Programmer
    Credit International

    Comment

    Working...