Search code examples
pythonpython-3.xdictionarynonetypekeyword-argument

map with kwargs returning nonetype python


Say I had a function, like this:

def test(*args, **kwargs):
    print(args, kwargs)

And I wanted to call it in a map object, like this:

obj = map(lambda var: test(var+1, var = var), [1, 2, 3])

When I print the values in it, it shows this:

>>> for i in obj:
    print(i)


(2,) {'var': 1}
None
(3,) {'var': 2}
None
(4,) {'var': 3}
None

Where are the None values coming from?


Solution

  • Your mapping function is printing, not returning values, so when you iterate the map object, i is being set to None over and over (None is returned by any function that doesn't explicitly return something else). To fix, change your function definition to something like:

    def test(*args, **kwargs):
        return args, kwargs
    

    so it returns the values rather than printing them, and your loop's print will see them instead of Nones.

    Alternatively, leave the function as is, and change the loop to:

    for i in obj:
        pass
    

    so you don't print the useless Nones from test. This is generally bad style mind you;map's mapping function should be side-effect free (printing is a side-effect) to match the functional nature ofmap. In general, functions thatprintinstead ofreturning are bad ideas; if youreturn, the caller canprintif they want to, or use areturnvalue programmatically, but if youprint`, the caller can't really do much (even if they capture it through cheesy hacks, they're stuck parsing it to do anything useful with it).