#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    78
    Rep Power
    2

    Can someone explain this code snippet to me?


    hey, found this little snippet on the net today, I cant seem to figure out why this works. What confuses me is the line "newdict = getdict(a=1, b=2,c=3)" because there is no variable called a, b or c declared yet.

    How does python know that these are strings and not variables?

    Code:
    def getdict(**kwrgs): 
          return kwrgs
    
    newdict = getdict(a=1, b=2,c=3)
    
    print(newdict)
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    100
    Rep Power
    2
    Originally Posted by leonnaley2
    hey, found this little snippet on the net today, I cant seem to figure out why this works. What confuses me is the line "newdict = getdict(a=1, b=2,c=3)" because there is no variable called a, b or c declared yet.
    In Python, you don't actually need to declare a variable before time, while writing positional arguments ('name = value' type). Python declares those names locally while you write the positional arguments.
    How does python know that these are strings and not variables?
    Whenever you define a function and in the arguments' place you use '**'; Python takes that the arguments/parameters passed-in will be positional arguments and when you return it, it returns the names and their values in a dictionary. It doesn't have anything to do with strings or numbers.
    Code:
    >>> def getdict(**kwrgs):
    	return kwrgs
    
    >>> newdict = getdict(a = 1, b = 2, c = 3)
    >>> print(newdict)
    >>> newdict = getdict(a = 'string', b = [1,2,3,4])
    
    {'a': 1, 'c': 3, 'b': 2}
    >>> print(newdict)		# No matter what happens, it'll return the result in a dictionary unless, of course, if you explicitly ask Python to print any other object type
    {'a': 'string', 'b': [1, 2, 3, 4]}
    
    # Now, when you explicitly ask Python to print a list:
    >>> def getdict(**kwrgs):
    	return list(kwrgs)
    
    >>> getdict(a = 1, b = 'string')
    ['a', 'b']
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    78
    Rep Power
    2
    Silly example I know, but it's still somewhat confusing to me though. Like in this instance where only one of the two places i call FirstLetter will actually be a variable, the other one will be a string by that name inside the new dict.

    I don't think I would be the only one not able to anticipate the output of this snippet though

    Code:
    def getdict(**kwrgs): 
          return kwrgs
    
    
    FirstLetter = "A"
    SecondLetter = "B"
    
    newdict = getdict(FirstLetter=FirstLetter, SecondLetter=SecondLetter)
    
    print(newdict)
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    So functions can be passed arguments essentially two ways. By position or by keyword.

    Take the simple function:
    python Code:
    def myfunc(a,b,c):
        print("a={} b={} c={}".format(a,b,c))
    Passing by position:
    Code:
    >>> myfunc(1,2,3)
    a=1 b=2 c=3
    Passing by keyword:
    Code:
    >>> myfunc(b=1,c=2,a=3)
    a=3 b=1 c=2
    Now if we were to try to pass something by keyword to this function that it didn't expect:
    Code:
    >>> myfunc(b=1,c=2,a=3,some_thing=4)
    Traceback (most recent call last):
      File "<interactive input>", line 1, in <module>
    TypeError: myfunc() got an unexpected keyword argument 'some_thing'
    >>>
    If you use **kwargs all unexpected keywords/values will be absorbed into the kwargs name as a dictionary.

    Let's change the function slightly:
    python Code:
    def myfunc(a,b,c,**kwargs):
        print("a={} b={} c={}".format(a,b,c))
        print("kwargs = {}".format(kwargs))
    and experiment a bit:
    Code:
    >>> myfunc(1,2,3,some_thing=4,another_thing="potato",and_another="spam")
    a=1 b=2 c=3
    kwargs = {'and_another': 'spam', 'another_thing': 'potato', 'some_thing': 4}
    Code:
    >>> myfunc(b=1,c=2,a=3,some_thing=4,another_thing="potato",and_another="spam")
    a=3 b=1 c=2
    kwargs = {'and_another': 'spam', 'another_thing': 'potato', 'some_thing': 4}
    -Mek
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    78
    Rep Power
    2
    Thank you very much, I think I get it now.

    Hopefully my brain will be able to interpret python code abit better from now on

IMN logo majestic logo threadwatch logo seochat tools logo