Function argument having value that is neither passed in by caller nor default value

I have a decorator like this:

def region_required(view_func):
    def new_view(request, ctx = {}, *args, **kw):
        import pdb; pdb.set_trace()
        ctx['regions'] = Region.objects.all()
        return view_func(request, context=ctx, *args, **kw)
    return new_view

I uses it to decorate view functions.

Today I noticed something really strange, the ctx (context) argument sometimes have data that belongs to last HTTP request. Then I narrowed it down to this decorator and found that somehow ctx has value when it should be {} here.

So I set a break point, and goes one level up, then I found its caller does NOT pass anything to it at all.

How can an argument has value that is neither passed in by caller nor default value?

Answers


You're using a mutable argument as a default parameter. Every time it's called without that argument, it will include the one you provided, including prior modifications. Use None as the default value instead, check for it, and if it is None, assign the empty dict in the body of the function.

def region_required(view_func):
    def new_view(request, ctx=None, *args, **kw):
        if ctx is None:
            ctx = {}
        import pdb; pdb.set_trace()
        ctx['regions'] = Region.objects.all()
        return view_func(request, context=ctx, *args, **kw)
    return new_view

Need Your Help

boost lock variable vector during update

c++ multithreading boost

several (2 or more) client threads need to run at a high frequency, but once every 1 minute a background service thread updates a variable used by the main threads.

Should I store spaces in my URLs in the database? If so, how do I encode them when putting them into <a href=“…”>?

asp.net-mvc razor data-annotations w3c-validation

In my blog, I store URIs on entities to allow them be customised (and friendly). Originally, they could contain spaces (eg. "/tags/ASP.NET MVC"), but the W3C validation says spaces are not valid.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.