1

So, I tried to search here and couldn't find any solution to that problem: I need to define a variable inside a "lambda".

I have that piece of code:

def z(t,s):exec("t=s")
r = type('', (), {
    '__init__': lambda t,*s: z("t.c",s),
    's': lambda t: (lambda t,*s: [t[::-1] for t in s])(*t.c),
    'l': lambda t: (lambda t,*s: list(s[::-1]))(*t.c),
    'd': lambda t: t.c
})

w = ["APPLE", "BEACH", "CITRUS"]
print r(*w).s()
print r(*w).l()
print r(*w).d()

Nothing works as it should work... Also when I call the function "d", it returns me this error:

AttributeError: '' object has no attribute 'c'

When it should return a tuple, something like:

('ALPHA', 'BRAVO', 'CHARLIE')

EDIT: Thanks guys, it works now, and is even smaller:

r=type('',(),{'__init__':lambda t,*s:setattr(t,'c',s),'s':lambda t:[t[::-1] for t in t.c],'l':lambda t:list(t.c[::-1]),'d':lambda t:t.c})
4
  • 6
    Why the heck are you doing this instead of just using a class statement? And are you aware that def can do literally anything lambda can? Commented Sep 14, 2014 at 4:17
  • Because it's a one-liner: def z(t,s):exec("t=s");r=type('',(),{'c':'','__init__':lambda t,*s:z(t.c,s),'s':lambda t:(lambda t,*s:[t[::-1] for t in s])(*t.c),'l':lambda t:(lambda t,*s:list(s[::-1]))(*t.c),'d':lambda t:t.c}) Commented Sep 14, 2014 at 4:18
  • 5
    "Because it's a one-liner" isn't a good reason to do things, especially when your one-liner doesn't fit on a line anyway. Commented Sep 14, 2014 at 4:20
  • It does fit on a line. Commented Sep 14, 2014 at 4:24

1 Answer 1

2

You need to use setattr to set an attribute: (If you want something like self.c = s)

'__init__': lambda t,*s: setattr(t, 'c', s),

>>> r = type('', (), {
...     '__init__': lambda t,*s: setattr(t, 'c', s),
...     's': lambda t: (lambda t,*s: [t[::-1] for t in s])(*t.c),
...     'l': lambda t: (lambda t,*s: list(s[::-1]))(*t.c),
...     'd': lambda t: t.c
... })
>>>
>>> w = ["APPLE", "BEACH", "CITRUS"]
>>> print r(*w).s()
['HCAEB', 'SURTIC']
>>> print r(*w).l()
['CITRUS', 'BEACH']
>>> print r(*w).d()
('APPLE', 'BEACH', 'CITRUS')
Sign up to request clarification or add additional context in comments.

3 Comments

@WilliamFernandes, Inner lambdas in s and l is redundant: 's': lambda t: [t[::-1] for t in t.c[1:]] , 'l': lambda t: list(t.c[1:][::-1])
@WilliamFernandes, Maybe you wanted this? 's': lambda t: [t[::-1] for t in t.c], 'l': lambda t: list(t.c[::-1]),
@WilliamFernandes, As others commented, avoid one-liner. It's hard to understand; hard to maintain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.