Mutable default values for function parameters

Ignacio Vazquez-Abrams ignacio at openservices.net
Thu Oct 4 18:18:24 EDT 2001


On Thu, 4 Oct 2001, Ignacio Vazquez-Abrams wrote:

> On Thu, 4 Oct 2001, Brian Quinlan wrote:
>
> > Here is my proposed expression:
> >
> > d = ((d is not None and [d]) or [[]])[0]
> >
> > Here is the test:
> >
> > def test(d = None):
> >     return ((d is not None and [d]) or [[]])[0]
> >
> > assert test() == []
> > assert test(None) == []
> > assert test(0) == 0
> > assert test('') == ''
> > assert test(5) == 5
> > assert test([1,2,3]) == [1,2,3]
> >
> > I believe that those are the semantics that you are looking for? And
> > so easy to understand...
>
> This is your brain on drugs. Any questions? ;)

Oh wait, I found another one:

---
def f(d=None):
  return [d, []][d==None]
---

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list