Global Variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bob Then

    #1

    Global Variables

    If I have a module File
    which has some fucontions but I need globals filename and path how can I
    set them so I can change them because I tryed.

    filename="log.t xt"
    path="/home/Bob/"

    def change_filename ():
    filename=raw_in put()

    def change_path():
    path=raw_input( )

    they don't change and without the declarations there not global.

    Help Please


  • George Sakkis

    #2
    Re: Global Variables

    Use 'global':

    def change_filename ():
    global filename
    filename=raw_in put()


    def change_path():
    global path
    path=raw_input( )


    Even better, don't use globals at all; in 99% if the time, there are
    better ways to achieve the same effect.

    George

    Comment

    • Tim Roberts

      #3
      Re: Global Variables

      "Bob Then" <Bob_then@yahoo .com.au> wrote:
      [color=blue]
      >If I have a module File
      >which has some fucontions but I need globals filename and path how can I
      >set them so I can change them because I tryed.
      >
      >filename="log. txt"
      >path="/home/Bob/"
      >
      >def change_filename ():[/color]
      global filename[color=blue]
      > filename=raw_in put()
      >
      >def change_path():[/color]
      global path[color=blue]
      > path=raw_input( )
      >
      >they don't change and without the declarations there not global.[/color]

      However, the reason that must be stated explicitly is because it's a bad
      practice. It means that your function has "side effects" beyond just
      returning a value or set of values. This kind of thing is a better
      solution:

      def change_filename ():
      return raw_input()

      def change_path()
      return raw_input()

      filename = change_filename ()
      path = change_path()
      --
      - Tim Roberts, timr@probo.com
      Providenza & Boekelheide, Inc.

      Comment

      Working...