Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #49476 > unrolled thread

Stupid ways to spell simple code

Started byChris Angelico <rosuav@gmail.com>
First post2013-06-30 16:06 +1000
Last post2013-07-02 00:33 -0700
Articles 17 — 10 participants

Back to article view | Back to comp.lang.python


Contents

  Stupid ways to spell simple code Chris Angelico <rosuav@gmail.com> - 2013-06-30 16:06 +1000
    Re: Stupid ways to spell simple code Rick Johnson <rantingrickjohnson@gmail.com> - 2013-06-30 07:58 -0700
      Re: Stupid ways to spell simple code Joshua Landau <joshua.landau.ws@gmail.com> - 2013-06-30 16:08 +0100
      Re: Stupid ways to spell simple code Chris Angelico <rosuav@gmail.com> - 2013-07-01 01:20 +1000
      Re: Stupid ways to spell simple code Ian Kelly <ian.g.kelly@gmail.com> - 2013-06-30 11:26 -0600
    Re: Stupid ways to spell simple code Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-06-30 17:36 +0000
      Re: Stupid ways to spell simple code Roy Smith <roy@panix.com> - 2013-06-30 13:44 -0400
      Re: Stupid ways to spell simple code Joshua Landau <joshua.landau.ws@gmail.com> - 2013-06-30 22:52 +0100
    Re: Stupid ways to spell simple code Neil Cerutti <neilc@norwich.edu> - 2013-07-01 12:59 +0000
      Re: Stupid ways to spell simple code Chris Angelico <rosuav@gmail.com> - 2013-07-01 23:14 +1000
      Re: Stupid ways to spell simple code Joshua Landau <joshua.landau.ws@gmail.com> - 2013-07-01 17:30 +0100
      Re: Stupid ways to spell simple code Marcin Szamotulski <mszamot@gmail.com> - 2013-07-01 20:36 +0100
        Re: Stupid ways to spell simple code Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-07-01 22:09 +0000
          Re: Stupid ways to spell simple code 88888 Dihedral <dihedral88888@gmail.com> - 2013-07-01 21:16 -0700
          Re: Stupid ways to spell simple code Marcin Szamotulski <mszamot@gmail.com> - 2013-07-02 07:22 +0100
      Re: Stupid ways to spell simple code Chris Angelico <rosuav@gmail.com> - 2013-07-02 02:32 +1000
    Re: Stupid ways to spell simple code Russel Walker <russ.pobox@gmail.com> - 2013-07-02 00:33 -0700

#49476 — Stupid ways to spell simple code

FromChris Angelico <rosuav@gmail.com>
Date2013-06-30 16:06 +1000
SubjectStupid ways to spell simple code
Message-ID<mailman.4021.1372572404.3114.python-list@python.org>
There's a bit of a discussion on python-ideas that includes a function
that raises StopIteration. It inspired me to do something stupid, just
to see how easily I could do it...

On Sun, Jun 30, 2013 at 3:45 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
Re: [Python-ideas] "Iteration stopping" syntax
>>>> def stop():
> ...     raise StopIteration

Here's a much more insane way to spell that:

stop = (lambda: 0 and (yield 1))().__next__

So, here's a challenge: Come up with something really simple, and
write an insanely complicated - yet perfectly valid - way to achieve
the same thing. Bonus points for horribly abusing Python's clean
syntax in the process.

Go on, do your worst!

ChrisA

[toc] | [next] | [standalone]


#49490

FromRick Johnson <rantingrickjohnson@gmail.com>
Date2013-06-30 07:58 -0700
Message-ID<cd9a09fe-9d1a-441c-bc47-473674e8ac71@googlegroups.com>
In reply to#49476
On Sunday, June 30, 2013 1:06:35 AM UTC-5, Chris Angelico wrote:
> So, here's a challenge: Come up with something really simple, and
> write an insanely complicated - yet perfectly valid - way to achieve
> the same thing. Bonus points for horribly abusing Python's clean
> syntax in the process.

Chris, i'm sorry, but your challenge is decades too late. If you seek amusement you need look no further than the Python stdlib. If you REALLY want to be amused, peruse the "idlelib" -- not only is the code obfuscated, it also breaks PEP8 and the PYTHON ZEN many times over.  

[toc] | [prev] | [next] | [standalone]


#49491

FromJoshua Landau <joshua.landau.ws@gmail.com>
Date2013-06-30 16:08 +0100
Message-ID<mailman.4029.1372604966.3114.python-list@python.org>
In reply to#49490
On 30 June 2013 15:58, Rick Johnson <rantingrickjohnson@gmail.com> wrote:
> Chris, i'm sorry, but your challenge is decades too late. If you seek amusement you need look no further than the Python stdlib. If you REALLY want to be amused, peruse the "idlelib" -- not only is the code obfuscated, it also breaks PEP8 and the PYTHON ZEN many times over.

To translate: Not only is the code impossible to read, inefficient and
unmaintainable whilst being only shallowly correct, but, *GASP* it
sometimes *breaks* semi-arbitrary code *style* *suggestions*! How dare it!‽

[toc] | [prev] | [next] | [standalone]


#49492

FromChris Angelico <rosuav@gmail.com>
Date2013-07-01 01:20 +1000
Message-ID<mailman.4030.1372605628.3114.python-list@python.org>
In reply to#49490
On Mon, Jul 1, 2013 at 1:08 AM, Joshua Landau
<joshua.landau.ws@gmail.com> wrote:
> On 30 June 2013 15:58, Rick Johnson <rantingrickjohnson@gmail.com> wrote:
>> Chris, i'm sorry, but your challenge is decades too late. If you seek amusement you need look no further than the Python stdlib. If you REALLY want to be amused, peruse the "idlelib" -- not only is the code obfuscated, it also breaks PEP8 and the PYTHON ZEN many times over.
>
> To translate: Not only is the code impossible to read, inefficient and
> unmaintainable whilst being only shallowly correct, but, *GASP* it
> sometimes *breaks* semi-arbitrary code *style* *suggestions*! How dare it!‽

Yeah, I cannot seriously imagine that the stdlib does anything like
the example I gave :) Pity nobody else is offering further examples, I
thought this might be a fun thread.

ChrisA

[toc] | [prev] | [next] | [standalone]


#49500

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-06-30 11:26 -0600
Message-ID<mailman.4033.1372613209.3114.python-list@python.org>
In reply to#49490
On Sun, Jun 30, 2013 at 9:20 AM, Chris Angelico <rosuav@gmail.com> wrote:
> Yeah, I cannot seriously imagine that the stdlib does anything like
> the example I gave :) Pity nobody else is offering further examples, I
> thought this might be a fun thread.

Well, there is the "this" module.  But its code is not *that*
obfuscated, and maintainability is not really an issue there since it
is short and does nothing of actual importance.

[toc] | [prev] | [next] | [standalone]


#49502

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-06-30 17:36 +0000
Message-ID<51d06cb6$0$29999$c3e8da3$5496439d@news.astraweb.com>
In reply to#49476
On Sun, 30 Jun 2013 16:06:35 +1000, Chris Angelico wrote:

> So, here's a challenge: Come up with something really simple, and write
> an insanely complicated - yet perfectly valid - way to achieve the same
> thing. Bonus points for horribly abusing Python's clean syntax in the
> process.

Here's a trivially stupid way to find the length of an iterable:

sum(1 for obj in iterable)

(except it isn't actually stupid, if the iterable is an iterator, and you 
don't mind consuming it to find out home many items it had). This leads 
to an obvious obfuscation:

sum(('.' for obj in iterable), '').count('.')


but sadly Python, in a rare case of protecting you from shooting your own 
foot off, doesn't allow this. Never mind, we can defeat the safety catch 
on sum() and complicate the code at the same time:

sum(('.' for obj in iterable), type('S', (), 
    {'__add__': lambda self, o: o})()).count('.')


Obfuscated *and* quadratic performance. Do I win?

Wait, I can beat that. Sorting is too trivial in Python:

alist.sort()

Pfft! Where's the challenge in that? Let's use an O(n!) algorithm for 
sorting -- yes, n factorial -- AND abuse a generator expression for its 
side effect. As a bonus, we use itertools, and just for the lulz, I 
obfuscate as many of the names as I can:


from random import shuffle as OOO00O
from itertools import takewhile as OO0O0O, count as O0OO0O

OO0O00 = range(5)

list(OO0O0O(lambda O: any(O[O0] < O[O0-1] for O0 in 
    range(1, sum(('O' for O in O), type('O', (), 
    {'__add__': lambda O0O, OO0: OO0})()).count('O'))),
    (OOO00O(OO0O00) or OO0O00 for O in O0OO0O())))[0]



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#49503

FromRoy Smith <roy@panix.com>
Date2013-06-30 13:44 -0400
Message-ID<roy-C39981.13441530062013@70-1-84-166.pools.spcsdns.net>
In reply to#49502
In article <51d06cb6$0$29999$c3e8da3$5496439d@news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python@pearwood.info> wrote:

> On Sun, 30 Jun 2013 16:06:35 +1000, Chris Angelico wrote:
> 
> > So, here's a challenge: Come up with something really simple, and write
> > an insanely complicated - yet perfectly valid - way to achieve the same
> > thing. Bonus points for horribly abusing Python's clean syntax in the
> > process.
> 
> Here's a trivially stupid way to find the length of an iterable:
> 
> sum(1 for obj in iterable)

That's how you would do it in a map-reduce environment :-)

[toc] | [prev] | [next] | [standalone]


#49516

FromJoshua Landau <joshua.landau.ws@gmail.com>
Date2013-06-30 22:52 +0100
Message-ID<mailman.4044.1372629187.3114.python-list@python.org>
In reply to#49502
On 30 June 2013 18:36, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> wrote:
> Pfft! Where's the challenge in that? Let's use an O(n!) algorithm for
> sorting -- yes, n factorial -- AND abuse a generator expression for its
> side effect. As a bonus, we use itertools, and just for the lulz, I
> obfuscate as many of the names as I can:
>
>
> from random import shuffle as OOO00O
> from itertools import takewhile as OO0O0O, count as O0OO0O
>
> OO0O00 = range(5)
>
> list(OO0O0O(lambda O: any(O[O0] < O[O0-1] for O0 in
>     range(1, sum(('O' for O in O), type('O', (),
>     {'__add__': lambda O0O, OO0: OO0})()).count('O'))),
>     (OOO00O(OO0O00) or OO0O00 for O in O0OO0O())))[0]

I've got to say -- that last line got me for quite a while, especially
as the list of lists was returning a list of sorted lists!

For obfuscation, though, you want unicode. It's much harder to reason
about code that you can't read.

from itertools import count as æ, permutations as Æ, starmap as ð
[globals().setdefault("%c"%sum(ø.encode()),ß)for ø,ß in
vars(__builtins__).items()if ø!="vars"]
sorted = lambda ħ:ƿ(ƞ for ı in
φ(ƴ(lambda:ħ,æ),ń(0,ń(ħ)**(len(ħ)*2-1)*len(ħ)))for ƞ in Æ(ħ)if
ǂ(()).__eq__((ŕ(ð(ǂ(Ƽ(ƞ).pop()).__rpow__,φ(ŕ(œ(ƞ,ƴ(lambda:0,ħ)),()),1))),ħ),ı))[::-1]

print(sorted([4, -3, 4, 2, -1]))

This only works for integers (including negatives) and some things
that seem to do nothing but slow it down are needed to cover special
cases. This one takes about 3½ minutes on my computer -- it's got a
runtime efficiency of something along the lines of O( (L!) * ((L)**i)
)  for i being related to the elements in the list and L being the
length of the list.

That said, it's rather OK at sorting [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].


I know this is more oriented towards obfuscation of code than
obfuscation of technique, but --as I said-- I'm writing a library for
that. I'll be back when it's ready.

[toc] | [prev] | [next] | [standalone]


#49557

FromNeil Cerutti <neilc@norwich.edu>
Date2013-07-01 12:59 +0000
Message-ID<b3dcp4Fhl04U2@mid.individual.net>
In reply to#49476
On 2013-06-30, Chris Angelico <rosuav@gmail.com> wrote:
> So, here's a challenge: Come up with something really simple,
> and write an insanely complicated - yet perfectly valid - way
> to achieve the same thing. Bonus points for horribly abusing
> Python's clean syntax in the process.
>
> Go on, do your worst!

I've often thought it was redundant for Python to support 'if'
when it has dictionaries, cf the rationale for having no
'switch'.

valid_name = None
while not valid_name:
    name = input("Enter your name: ")
    valid_name = {
        True: lambda: print("No name longer than 20 letters."),
        False: lambda: True,
    }[len(name) > 20]()

Much better.

-- 
Neil Cerutti

[toc] | [prev] | [next] | [standalone]


#49559

FromChris Angelico <rosuav@gmail.com>
Date2013-07-01 23:14 +1000
Message-ID<mailman.4069.1372684465.3114.python-list@python.org>
In reply to#49557
On Mon, Jul 1, 2013 at 10:59 PM, Neil Cerutti <neilc@norwich.edu> wrote:
> On 2013-06-30, Chris Angelico <rosuav@gmail.com> wrote:
>> So, here's a challenge: Come up with something really simple,
>> and write an insanely complicated - yet perfectly valid - way
>> to achieve the same thing. Bonus points for horribly abusing
>> Python's clean syntax in the process.
>>
>> Go on, do your worst!
>
> I've often thought it was redundant for Python to support 'if'
> when it has dictionaries, cf the rationale for having no
> 'switch'.
>
> valid_name = None
> while not valid_name:
>     name = input("Enter your name: ")
>     valid_name = {
>         True: lambda: print("No name longer than 20 letters."),
>         False: lambda: True,
>     }[len(name) > 20]()
>
> Much better.

Good! Good! But, waaaah. Waaaah.

def get_name():
  while True:
    name = input("Enter your name: ")
    yield {
        True: lambda: print("No name longer than 20 letters."),
        False: lambda: name,
    }[len(name) > 20]()
name = next(filter(None,get_name()))

ChrisA

[toc] | [prev] | [next] | [standalone]


#49571

FromJoshua Landau <joshua.landau.ws@gmail.com>
Date2013-07-01 17:30 +0100
Message-ID<mailman.4071.1372696293.3114.python-list@python.org>
In reply to#49557
On 1 July 2013 14:14, Chris Angelico <rosuav@gmail.com> wrote:
> On Mon, Jul 1, 2013 at 10:59 PM, Neil Cerutti <neilc@norwich.edu> wrote:
>> On 2013-06-30, Chris Angelico <rosuav@gmail.com> wrote:
>>> So, here's a challenge: Come up with something really simple,
>>> and write an insanely complicated - yet perfectly valid - way
>>> to achieve the same thing. Bonus points for horribly abusing
>>> Python's clean syntax in the process.
>>>
>>> Go on, do your worst!
>>
>> I've often thought it was redundant for Python to support 'if'
>> when it has dictionaries, cf the rationale for having no
>> 'switch'.
>>
>> valid_name = None
>> while not valid_name:
>>     name = input("Enter your name: ")
>>     valid_name = {
>>         True: lambda: print("No name longer than 20 letters."),
>>         False: lambda: True,
>>     }[len(name) > 20]()
>>
>> Much better.
>
> Good! Good! But, waaaah. Waaaah.
>
> def get_name():
>   while True:
>     name = input("Enter your name: ")
>     yield {
>         True: lambda: print("No name longer than 20 letters."),
>         False: lambda: name,
>     }[len(name) > 20]()
> name = next(filter(None,get_name()))

Oh, cruel. But you can do worse. Who needs "while" when you have
filter(iter(FUNCTION, object()))?

def get_name():
    name = input("Enter your name: ")
    return [
        lambda: name,
        lambda: print("No name longer than 20 letters."),
    ][len(name) > 20]()

name = next(filter(None, iter(get_name, object())))


But who needs *any* of this! Defining functions is so old-hat. It's
all already in the standard library (using only assignments and function-calls):

from functools import partial
from operator import getitem, ge, methodcaller
from itertools import compress, tee
apply = methodcaller("__call__")
ret_true = partial(getitem, [True], 0)
print_invalid = partial(print, "No name longer than 20 letters.")
inputs = iter(partial(input, "Enter your name: "), ...)
inputs, valid = tee(inputs)
valid = map(len, valid)
valid = map(partial(ge, 20), valid)
side_effect_valid = map(partial(getitem, [print_invalid, ret_true]), valid)
side_effect_valid = map(apply, side_effect_valid)
valid_inputs = compress(inputs, side_effect_valid)
name = next(valid_inputs)


Which can be "neatly" expressed as two statements (I'm struggling to
got it to one without those evil lambdas):

from functools import partial
from operator import getitem, ge, methodcaller
from itertools import compress, tee

inputs, valid = tee(iter(partial(input, "Enter your name: "), ...))

name = next(
    compress(
        inputs,
        map(
            methodcaller("__call__"),
            map(
                partial(
                    getitem,
                    [
                        partial(print, "No name longer than 20 letters."),
                        partial(getitem, [True], 0)
                    ]
                ),
                map(
                    partial(ge, 20),
                    map(len, valid)
                )
            )
        )
    )
)


Beautiful, see?


Of course, the most powerful function deals with this much more quickly:

exec("""
while True:
    name = input("Enter your name: ")

    if len(name) <= 20:
        break

    else:
        print("No name longer than 20 letters.")
""")

[toc] | [prev] | [next] | [standalone]


#49588

FromMarcin Szamotulski <mszamot@gmail.com>
Date2013-07-01 20:36 +0100
Message-ID<mailman.4082.1372707405.3114.python-list@python.org>
In reply to#49557
On 17:30 Mon 01 Jul     , Joshua Landau wrote:
> On 1 July 2013 14:14, Chris Angelico <rosuav@gmail.com> wrote:
> > On Mon, Jul 1, 2013 at 10:59 PM, Neil Cerutti <neilc@norwich.edu> wrote:
> >> On 2013-06-30, Chris Angelico <rosuav@gmail.com> wrote:
> >>> So, here's a challenge: Come up with something really simple,
> >>> and write an insanely complicated - yet perfectly valid - way
> >>> to achieve the same thing. Bonus points for horribly abusing
> >>> Python's clean syntax in the process.
> >>>
> >>> Go on, do your worst!
> >>
> >> I've often thought it was redundant for Python to support 'if'
> >> when it has dictionaries, cf the rationale for having no
> >> 'switch'.
> >>
> >> valid_name = None
> >> while not valid_name:
> >>     name = input("Enter your name: ")
> >>     valid_name = {
> >>         True: lambda: print("No name longer than 20 letters."),
> >>         False: lambda: True,
> >>     }[len(name) > 20]()
> >>
> >> Much better.
> >
> > Good! Good! But, waaaah. Waaaah.
> >
> > def get_name():
> >   while True:
> >     name = input("Enter your name: ")
> >     yield {
> >         True: lambda: print("No name longer than 20 letters."),
> >         False: lambda: name,
> >     }[len(name) > 20]()
> > name = next(filter(None,get_name()))
> 
> Oh, cruel. But you can do worse. Who needs "while" when you have
> filter(iter(FUNCTION, object()))?
> 
> def get_name():
>     name = input("Enter your name: ")
>     return [
>         lambda: name,
>         lambda: print("No name longer than 20 letters."),
>     ][len(name) > 20]()
> 
> name = next(filter(None, iter(get_name, object())))
> 
> 
> But who needs *any* of this! Defining functions is so old-hat. It's
> all already in the standard library (using only assignments and function-calls):
> 
> from functools import partial
> from operator import getitem, ge, methodcaller
> from itertools import compress, tee
> apply = methodcaller("__call__")
> ret_true = partial(getitem, [True], 0)
> print_invalid = partial(print, "No name longer than 20 letters.")
> inputs = iter(partial(input, "Enter your name: "), ...)
> inputs, valid = tee(inputs)
> valid = map(len, valid)
> valid = map(partial(ge, 20), valid)
> side_effect_valid = map(partial(getitem, [print_invalid, ret_true]), valid)
> side_effect_valid = map(apply, side_effect_valid)
> valid_inputs = compress(inputs, side_effect_valid)
> name = next(valid_inputs)
> 
> 
> Which can be "neatly" expressed as two statements (I'm struggling to
> got it to one without those evil lambdas):
> 
> from functools import partial
> from operator import getitem, ge, methodcaller
> from itertools import compress, tee
> 
> inputs, valid = tee(iter(partial(input, "Enter your name: "), ...))
> 
> name = next(
>     compress(
>         inputs,
>         map(
>             methodcaller("__call__"),
>             map(
>                 partial(
>                     getitem,
>                     [
>                         partial(print, "No name longer than 20 letters."),
>                         partial(getitem, [True], 0)
>                     ]
>                 ),
>                 map(
>                     partial(ge, 20),
>                     map(len, valid)
>                 )
>             )
>         )
>     )
> )
> 
> 
> Beautiful, see?
> 
> 
> Of course, the most powerful function deals with this much more quickly:
> 
> exec("""
> while True:
>     name = input("Enter your name: ")
> 
>     if len(name) <= 20:
>         break
> 
>     else:
>         print("No name longer than 20 letters.")
> """)
> -- 
> http://mail.python.org/mailman/listinfo/python-list


Here is another example which I came across when playing with
generators, the first function is actually quite useful, the second
generator is the whole fun:

from functools import wraps
def init(func):
    """decorator which initialises the generator
    """
    @wraps(func)
    def inner(*args, **kwargs):
        g = func(*args, **kwargs)
        g.send(None)
        return g
    return inner

@init
def gen(func):
     x = (yield)
     while True:
         x = (yield func(x))


now if you have function f
def f(arg):
    return arg**2

then calling f(5) is the same as

g = gen(f)
g.send(5)


I wrote a blog post where I did include this as a `useless` example:
http://pycorner.herokuapp.com/blog/5

Best regards,
Marcin

[toc] | [prev] | [next] | [standalone]


#49596

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2013-07-01 22:09 +0000
Message-ID<51d1fe0d$0$29973$c3e8da3$5496439d@news.astraweb.com>
In reply to#49588
On Mon, 01 Jul 2013 20:36:29 +0100, Marcin Szamotulski wrote:

> Here is another example which I came across when playing with
> generators, the first function is actually quite useful, the second
> generator is the whole fun:
> 
> from functools import wraps
> def init(func):
>     """decorator which initialises the generator """
>     @wraps(func)
>     def inner(*args, **kwargs):
>         g = func(*args, **kwargs)
>         g.send(None)
>         return g
>     return inner
> 
> @init
> def gen(func):
>      x = (yield)
>      while True:
>          x = (yield func(x))
> 
> 
> now if you have function f
> def f(arg):
>     return arg**2
> 
> then calling f(5) is the same as
> 
> g = gen(f)
> g.send(5)



I think you must be missing an important part of the trick, because 
calling f(5) returns 25. It's not:

@gen
def f(arg):
    return arg**2


because that raises TypeError.




-- 
Steven

[toc] | [prev] | [next] | [standalone]


#49606

From88888 Dihedral <dihedral88888@gmail.com>
Date2013-07-01 21:16 -0700
Message-ID<875111a8-4784-4590-aecd-3c505e26126b@googlegroups.com>
In reply to#49596
Steven D'Aprano於 2013年7月2日星期二UTC+8上午6時09分18秒寫道:
> On Mon, 01 Jul 2013 20:36:29 +0100, Marcin Szamotulski wrote:
> 
> 
> 
> > Here is another example which I came across when playing with
> 
> > generators, the first function is actually quite useful, the second
> 
> > generator is the whole fun:
> 
> > 
> 
> > from functools import wraps
> 
> > def init(func):
> 
> >     """decorator which initialises the generator """
> 
> >     @wraps(func)
> 
> >     def inner(*args, **kwargs):
> 
> >         g = func(*args, **kwargs)
> 
> >         g.send(None)
> 
> >         return g
> 
> >     return inner
> 
> > 
> 
> > @init
> 
> > def gen(func):
> 
> >      x = (yield)
> 
> >      while True:
> 
> >          x = (yield func(x))
> 
> > 
> 
> > 
> 
> > now if you have function f
> 
> > def f(arg):
> 
> >     return arg**2
> 
> > 
> 
> > then calling f(5) is the same as
> 
> > 
> 
> > g = gen(f)
> 
> > g.send(5)
> 
> 
> 
> 
> 
> 
> 
> I think you must be missing an important part of the trick, because 
> 
> calling f(5) returns 25. It's not:
> 
> 
> 
> @gen
> 
> def f(arg):
> 
>     return arg**2
> 
> 
> 
> 
> 
> because that raises TypeError.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

Lets be serious about generators and iterators.

A generator can be used only once in a program
is different from a a generator method of a class that 
can produce several instances with generators of the same kind
but operated in each instance of the class.

[toc] | [prev] | [next] | [standalone]


#49613

FromMarcin Szamotulski <mszamot@gmail.com>
Date2013-07-02 07:22 +0100
Message-ID<mailman.4094.1372746145.3114.python-list@python.org>
In reply to#49596
On 22:09 Mon 01 Jul     , Steven D'Aprano wrote:
> On Mon, 01 Jul 2013 20:36:29 +0100, Marcin Szamotulski wrote:
> 
> > Here is another example which I came across when playing with
> > generators, the first function is actually quite useful, the second
> > generator is the whole fun:
> > 
> > from functools import wraps
> > def init(func):
> >     """decorator which initialises the generator """
> >     @wraps(func)
> >     def inner(*args, **kwargs):
> >         g = func(*args, **kwargs)
> >         g.send(None)
> >         return g
> >     return inner
> > 
> > @init
> > def gen(func):
> >      x = (yield)
> >      while True:
> >          x = (yield func(x))
> > 
> > 
> > now if you have function f
> > def f(arg):
> >     return arg**2
> > 
> > then calling f(5) is the same as
> > 
> > g = gen(f)
> > g.send(5)
> 
> 
> 
> I think you must be missing an important part of the trick, because 
> calling f(5) returns 25. It's not:
> 
> @gen
> def f(arg):
>     return arg**2
> 
> 
> because that raises TypeError.
> -- 
> Steven
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Sure it does,  you're now supposed to use .send method instead of
calling it but this is just different syntax.  If you want to call it
use this :

def identity(func):
    @init
    def gen(func):
        x = (yield)
        while True:
            x = (yield func(x))
    return gen(func).send

Now you will get:

>>> @identity
>>> def f(a): a+1
...
>>> f(0)
1

Best regards,
Marcin

[toc] | [prev] | [next] | [standalone]


#49618

FromChris Angelico <rosuav@gmail.com>
Date2013-07-02 02:32 +1000
Message-ID<mailman.4105.1372749626.3114.python-list@python.org>
In reply to#49557
On Tue, Jul 2, 2013 at 2:30 AM, Joshua Landau
<joshua.landau.ws@gmail.com> wrote:
> Beautiful, see?


Truly a work of art! I am awed.

ChrisA

[toc] | [prev] | [next] | [standalone]


#49625

FromRussel Walker <russ.pobox@gmail.com>
Date2013-07-02 00:33 -0700
Message-ID<bc53942a-fb26-4ac9-a6a8-8cac2b35b2d4@googlegroups.com>
In reply to#49476
On Sunday, June 30, 2013 8:06:35 AM UTC+2, Chris Angelico wrote:
> There's a bit of a discussion on python-ideas that includes a function
> 
> that raises StopIteration. It inspired me to do something stupid, just
> 
> to see how easily I could do it...
> 
> 
> 
> On Sun, Jun 30, 2013 at 3:45 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
> 
> Re: [Python-ideas] "Iteration stopping" syntax
> 
> >>>> def stop():
> 
> > ...     raise StopIteration
> 
> 
> 
> Here's a much more insane way to spell that:
> 
> 
> 
> stop = (lambda: 0 and (yield 1))().__next__
> 
> 
> 
> So, here's a challenge: Come up with something really simple, and
> 
> write an insanely complicated - yet perfectly valid - way to achieve
> 
> the same thing. Bonus points for horribly abusing Python's clean
> 
> syntax in the process.
> 
> 
> 
> Go on, do your worst!
> 
> 
> 
> ChrisA

Here's a way to count items in a string.

def count(string, x):
    return len(''.join(string)) - len(''.join(string).replace(x, '')) / len(x)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web