Thursday, March 31, 2011

Send Info from Script to Module Python

Hi I wonder how you can send info over to a module

An Example main.py Looks like this

from module import *
print helloworld()

module.py looks like this

def helloworld():    
    print "Hello world!"

Anyway i want to send over info from main.py to module.py is it possible?

From stackoverflow
  • It is not clear what you mean by "send info", but if you but the typical way of passing a value would be with a function parameter.

    main.py:

    helloworld("Hello world!")
    

    module.py

    def helloworld(message):
        print message
    

    Is that what your looking for? Also the two uses of print in your example are redundant.

    Addendum: It might be useful for you to read the Python documentation regarding function declarations, or, alternatively, most Python introductory tutorials would cover the same ground in fewer words. Anything you read there is going to apply equally regardless of whether the function is in the same module or another module.

  • Yes. You can either send over information when calling functions/classes in module, or you can assign values in module's namespace (not so preferable).

    As an example:

    # module.py
    # good example
    def helloworld(name):
        print "Hello, %s" % name
    
    # main.py
    # good example
    import module
    module.helloworld("Jim")
    

    And for the bad: don't do it:

    # module.py
    # bad example
    def helloworld(): 
        print "Hello, %s" % name
    
    # main.py
    # bad example
    import module
    module.name = "Jim"
    module.helloworld()
    

0 comments:

Post a Comment