Results 1 to 9 of 9

Thread: python returns variable problem

  1. #1
    Join Date
    Jan 2012
    Beans
    161

    python returns variable problem

    ok so here is my code:

    Code:
    global a
    
    
    def determineTypes(arg1, arg2):
        if type(arg1) is not type(arg2):
            print 'WARNING...OBJECTS NOT SIMILAR...ERROR MAY GENERATE...'
            print 'press enter to continue.'
            raw_input('>')
            adder(arg1,arg2)
        else:
            adder(arg1,arg2)
    
    
    def adder(arg1, arg2):
        if type(arg1) is list:
            arg1.append(arg2)
    	return arg1
        elif type(arg1) is str:
            a = arg1 + arg2
            return a
        elif type(arg1) is dict:
            for key in arg2:
                a = arg1
                a[key] = arg2[key]
                return a
    
    
        elif type(arg1) is int or float:
            a = arg1 + arg2
            return a
    
    
        else:
            #should not happen, just a placeholder
            pass
        
    
    
    def begin():
        print 'what is item one?'
        item1 = raw_input('>')
        print 'what is item two?'
        item2 = raw_input('>')
        determineTypes(item1,item2)
    How come none of the values for a get returned as 'a'. After running the program, say:

    Code:
    adder.determineTypes(3,4)
    print adder.a
    I get an error, or if i switch the values of arg1 and arg2 i get 'None'. Why is that?

  2. #2
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: python returns variable problem

    It looks like you expect your module to behave like a class. You can't access a like that, you need something like

    Code:
    class Adder(object):
    
        def determineTypes(self, arg1, arg2):
            if type(arg1) is not type(arg2):
                print 'WARNING...OBJECTS NOT SIMILAR...ERROR MAY GENERATE...'
                print 'press enter to continue.'
                raw_input('>')
                self.adder(arg1,arg2)
            else:
                self.adder(arg1,arg2)
    
        def adder(self, arg1, arg2):
            if type(arg1) is list:
                arg1.append(arg2)
                self.a = arg1
            elif type(arg1) is str:
                self.a = arg1 + arg2
            elif type(arg1) is dict:
                for key in arg2:
                    self.a = arg1
                    self.a[key] = arg2[key]
            elif type(arg1) in [int, float]:
                self.a = arg1 + arg2
            else:
                #should not happen, just a placeholder
                pass
    Then

    Code:
    >>> import adder
    >>> add = adder.Adder()
    >>> add.determineTypes(.5, .3)
    >>> add.a
    0.8
    >>> add.determineTypes(1,2)
    >>> add.a
    3
    P.S.: You should also consider switching to Python 3, there doesn't seem to be anything stopping you.
    Last edited by Bachstelze; July 8th, 2013 at 01:43 AM.
    「明後日の夕方には帰ってるからね。」


  3. #3
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: python returns variable problem

    However, if you don't want to write a class, then just importing (import adder) will make your code work without any trouble.

  4. #4
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: python returns variable problem

    Quote Originally Posted by nvteighen View Post
    However, if you don't want to write a class, then just importing (import adder) will make your code work without any trouble.
    I must be doing something wrong then...

    Code:
    >>> import adder
    >>> adder.determineTypes(3,4)
    >>> adder.a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'a'
    「明後日の夕方には帰ってるからね。」


  5. #5
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: python returns variable problem

    Quote Originally Posted by Bachstelze View Post
    I must be doing something wrong then...

    Code:
    >>> import adder
    >>> adder.determineTypes(3,4)
    >>> adder.a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'a'
    Just when I thought I knew Python really well, it hits me with this one... *facepalm*... globals are module-scoped.

  6. #6
    Join Date
    Jan 2012
    Beans
    161

    Re: python returns variable problem

    Thanks guys lol. Im just doing it class based now.

  7. #7
    Join Date
    Jan 2012
    Beans
    161

    Re: python returns variable problem

    how do I mark this thread as complete?

  8. #8
    Join Date
    Feb 2009
    Beans
    1,469

    Re: python returns variable problem

    Edit the original post and add [Solved] to the title.

    For posterity, and in case you see something like this again: An assignment within an inner scope masks or "shadows" variables in outer scopes. To prevent this, you need to put a "global" statement (or "nonlocal", in Python 3) in the inner scope, which tells Python "I want to use the `a' in the outer scope, even though I'm assigning to it." This is kind of a gotcha and easy to overlook.

    Code:
    a = "hello"
    def greet(target):
        print a, target
    greet("world")
    will print "hello world", but
    Code:
    a = "hello"
    def greet(target):
        print a, target
        a = "hi"
    greet("world")
    raises an error.

    You can fix your original program (well, that particular bug) by moving the "global a" declaration inside the definition of adder().

  9. #9
    Join Date
    Apr 2013
    Location
    43.49°N 7.46°E
    Beans
    117
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: python returns variable problem

    according to the programming recommendations contained in the PEP8, you should use:
    1. Code:
      if isinstance(obj, type)
      instead of
      Code:
      if type(obj) is type(value of the type to be checked)
    2. Code:
      ''.join([string1, string2, ...])
      instead of
      Code:
      string1 = string1 + string2 + ...

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •