#1
  1. No Profile Picture
    inexperienced and useless
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2001
    Location
    Stevenage, uk
    Posts
    10
    Rep Power
    0

    Question Defining a variable within a function as global


    At the moment I have a function which gives a result, I need this result to use it in a different function. However, because the variable is defined within the function, it's scope is only local, therefore I cannot use it outside of the function. I cannot just define it outside of the function because all of the function creates this variable.

    I have tried usine the following type of syntax:

    global struc_smi
    struc_smi = f.read

    however this still doesn't seem to work as I get errors saying that struc_smi is not defined.

    Please help
  2. #2
  3. No Profile Picture
    Python Prophet
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2001
    Location
    Amersfoort, The Netherlands
    Posts
    45
    Rep Power
    14
    First of all: global is considered evil. Don't use it. It can lead to some very irritating debugging. You could just do it this way:

    struc_smi = function()
    foo = bar(struc_smi)

    But, to fix the error, you should first define the variable outside of the function before using global inside a function. global doesn't define a variable, it makes it usable within the function.
    Some people, when confronted with a problem, think I know, I'll use regular expressions. Now they have two problems. - Jamie Zawinski, in comp.lang.emacs
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Washington State
    Posts
    7
    Rep Power
    0

    Same problem with JavaScript


    What if the definition of the variable is decided by the function? I have much the same problem with JavaScript, I'd like to run a function with a variable defined by another functions output. Any chance someone could help me please? I don't know Python, but this is the only place I found most closely addresses my problem. Thanks.
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    I dont see the problem, not that I really use globals so much; as Taradino said: evil . Anyway I've done you a little example:

    Code:
    >>> def foo(argument):
    	return argument + 1
    
    >>> def bar(argument):
    	return argument + 5
    
    >>> globalVariable = foo(6)
    >>> globalVariable
    7
    >>> globalVariable = bar(globalVariable)
    >>> globalVariable
    12
    >>> 
    >>> 
    >>> def foo():
    	global globalVariable
    	globalVariable += 1
    
    >>> def bar():
    	global globalVariable
    	globalVariable += 5
    
    >>> globalVariable = 6
    >>> foo()
    >>> globalVariable
    7 
    >>> bar()
    >>> globalVariable
    12
    >>>
    The first example is obviously not use globals, but it does show the preferred way of doing this kind of thing [editing a the value of a variable]. One advantage of this, besides making code much more readable is that the function can also be used with other variables .

    But its the second example you want to be looking at. As you can see, foo() and bar() can be defined before our globalVariable just as long as it is defined when the functions are called!

    Hope you find this useful, enjoy!

    Mark.
    programming language development: www.netytan.com Hula

  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Washington State
    Posts
    7
    Rep Power
    0
    Thanks man. Much appreciated.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Isle of dogs
    Posts
    68
    Rep Power
    11
    Originally Posted by gaston9x19
    Thanks man. Much appreciated.
    Listen to Taradino, you don't want to use global variable unless you consider yourself a VB hating, god fearing, object oriented purist. I guess it might be ok if the application you are creating is very small and good programming practice is not necessary, but I highly doubt it.

    I thought there would be a big OOP revelations were even schoolgirls know about good programming design. But i guess it was not to be, I guess that the same with career in programming but I am ganna just give up and let VB and Java programmers create bad code while , I am working as a crummy refusge collector , you have another thing coming.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    35
    What if the definition of the variable is decided by the function?
    That isn't a problem because functions can return values, as Netytan demonstrates, but if you mean the type of the variable is decided by the function (integer, string, etc) that also isn't a problem - you can use type(x) to find out what type the returned variable is.

    Code:
    >>> type("hello")
    <type 'str'>
    
    >>> type(123)
    <type 'int'>
    Although in that case, it could likely be re-written to avoid that sort of checking.

    I have much the same problem with JavaScript, I'd like to run a function with a variable defined by another functions output.
    Well, apart from me not quite getting what you mean here, you might be in a situation where a custom class could help.
    Objects are much nicer than global variables, really.

    e.g.
    Code:
    class SpeedStore:
        def __init__(self, mph):
            self.speed = mph
    
        def speedUp(change=1):
            self.speed += change
            print self.speed
    
        def slowDown(change=1):
            self.speed -= change
            print self.speed
    
    carSpeed = SpeedStore(mph=55)
    print carSpeed.speed
    carSpeed.speedUp(10)
    carSpeed.slowDown(5)
    
    bikeSpeed = SpeedStore(mph=10)
    print bikeSpeed.speed
    The value defined in __init__ (.speed) is available through the whole class (as a global would be). The functions in the class (speedUp, slowDown) can change and use it.

    Outside the class, you can also get to any specific instance of it, using the carSpeed.speed form (unlike a global).

    It's a bit like using a global, but without many of the problems -
    e.g. you can have more than one instance of the class using it without conflicting names. You have to say "bikeSpeed.speed" instead of just "speed", so you're never confused about where the variable is coming from, or where it is defined. You can trace where it is being used, and how, much more easily than global variables. You don't need to define "global x" at the top of every function that uses it.

    If you want to post some more sample code, it might be clearer what would help you...
  14. #8
  15. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Personally I prefer to use isinstance() over type() since the type() function only works with the built-in types! Other types of variable will be labelled 'instance'. Observe .

    Code:
    >>> class Test1:
    	def __init__(self):
    		self.something = None
    		
    >>> class Test2:
    	def __init__(self):
    		self.something = None
    		
    >>> test0 = 'Im a string'
    >>> test1 = Test1()
    >>> test2 = Test2()
    >>> 
    >>> type(test0)
    <type 'str'>
    >>> type(test1)
    <type 'instance'>
    >>> type(test2)
    <type 'instance'>
    >>>
    >>> type(test1) == type(Test2())
    True
    >>> isinstance(test1, Test1)
    True
    >>> isinstance(test2, Test2)
    True
    >>> isinstance(test1, Test2)
    False
    >>>
    Besides looking cleaner, this can be very useful .

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo