How To RUIN A Function In Python

preview_player
Показать описание
How to ruin a function in Python. #Python #Code #Shorts
Рекомендации по теме
Комментарии
Автор

my favorite part of the video was when you told us how to fix it

henrypeterson
Автор

If you want a fresh dict :

def func(key, value, d=None):
if d is None:
d = {}
d[key] = value
print(d)

SyntharaPrime
Автор

While brevity is certainly a necessity for these shorts, mentioning that this also applies to lists and other mutable data structures would be helpful...

ericcrowell
Автор

In Python, if an object of "mutable" feature is declared as the default value of a function argument and a variable is created through that default value, the variable has the character of a static variable.

Some sites say that if the default value of an argument is mutable, it becomes a global variable.

The life time of the variable is global, but the scope is inside the function, so it would be more correct to view it as a static variable rather than a global variable.

So when you create a function or method, it's better to avoid using "mutable" default value.

cheers,

livewiththeflow
Автор

Simple rule: no default mutable objects in function arguments.

ЕвгенийКрасилов-оо
Автор

More easier way-
def func(key, value):
d={key:value}
print(d)

MK-youtube
Автор

Solution:
def myfunc(key, value, myd:dict=None):
if myd is None:
myd=dict()
myd[key]=value
print(myd)

You can also always build a helper function:
def myhelper(key, value):
myfunc(key, value, {})

oida
Автор

When a parameter is optional (and is not of a generic type), Python treats it like a private static variable to the function object you are defining. This variable is used only when a value for that parameter is not given.
When you pass something to an optional parameter, it does not overwrite the function's variable for that parameter, but instead is used in place.
Here is an example bit of code demonstrating how this works:

class MyClass:
    def __init__(self, x):
        self.x = x

def test(foo=None, bar=MyClass(1)):
    if foo != None:
        bar.x = foo
    print(bar.x)

test(2) # 2
test() # 2
test(bar=MyClass(3)) # 3
test() # 2


The value 2 is being saved to the object contained by the bar variable. When you try to overwrite bar=MyClass(3), it does not save the value, instead only using MyClass(3) instead of the existing bar variable.

In the end, be careful about non-generic types in Python. Python typically does call-by-reference for non-generic types, which can cause you to modify objects you might want to keep normally. To only do call-by-value, use the deepcopy function from the copy library.

basilicon.
Автор

Key Takeaway: Never use mutable objects as default values ​​in function definitions. Use immutable values ​​and initialize mutable objects inside the function if necessary. This practice avoids unwanted side effects and ensures that each function call is independent, resulting in safer and more predictable code.

palmerimsoaresdesa
Автор

This is one of the worst designed behavior i saw i CS

emakei
Автор

I'm confused as to why anyone would think that the code you wrote wouldn't do that? You never initialize the dictionary in the function.

To fix this, just add the line "d={}" to the beginning of your function.

def func(a, b, d={}):
d = {}
d[a] = b
print(d)

func(1, 2) #output: {1:2}
func(3, 4) #output: {3:4}

This is because Python will continue storing your variables even after you're done using them. The "d = {}" as a function parameter just tells Python to use the empty dict as default. But d was changed with running the first function, so that d becomes our default.

Similar to this is using a variable defined within a loop later will not do what you expect.

def loop():
for i in range(3):
print(i)
print()
print(i)

loop()
#output: 0, 1, 2, , 2

Python remembers!!

skerJG
Автор

To correct the problem:

def func(key, value, d=None):
d = d or {}
d[key] = value
print(d)

The line d = d or {} will pass a NEW dictionary to d if it's None, otherwise will do nothing

adryelbarros
Автор

Solution is to set “d” as a default argument to None. Then create an empty dict inside the function after checking if d is None.
It would look like this:

def func(key, value, d=None):
If d is None:
d = {}
d[key] = value
print(d)

rakanareekan
Автор

Great video. I liked when you showed us the right way to do it

mattyice
Автор

The following should work:

def func(key, value, d={}):
d[key] = value
print(d)
d.clear()

func('a', 10)
func('b', 20)

ButchCassidyAndSundanceKid
Автор

yeah this is one of the stupidest things i have encountered in python

ksaittis
Автор

"You'll notice something *func-y* "
:)

asgard_
Автор

You can achieve a default dictionary with the partial function. Than the dictionaries are not shared. If you decorate the original function, the function would even have the same name.
There can be some conflicts between positional and keyword arguments when using partial, so I would force the dictionary to be passed as keyword argument with *, in the parameters.

Temo
Автор

You can also just do this:
def func(key, value, d={}.copy()):
pass

akgamerV
Автор

Kwargs defaults must be immutable types. In this particular case, set default to a sentinel, you can do so by creating an instance like: NOTHING=object() outside of the function, if d is NOTHING: d={}

NoProblem