#esoteric-python

1 messages · Page 88 of 1

brisk zenith
#

meanwhile in the last staff meeting i attended, we were invaded by dinosaurs because of how long ago it was >.<

brazen geyser
#

@grave rover did you have a switch implementation by any chance

grave rover
#

Uhhh

#

I vaguely remember one

#

I think it was a collab between me and Laura?

#
a, b, c = 1, 2, 3

with switch(a, b, c):
    with case(lambda a, b, c: a < b < c):
        print('ayy 0')

        with switch(b, a, c):
            with case(2, 1, 3):
                print('nested switch!')

            with case(1, 2, 3):
                print('this wont be printed')

    with case(1, 2, 3):
        print('ayy 1')

        with case(lambda a, b, c: b == 2):
            print('holy shit a nested case!')
        switch_break()

    with case(1, 2, 3):
        print('ayy 2')
#

I can't recall if this handled nested switch statements properly though

#

@brazen geyser

brazen geyser
#

who is laura

#

also this is my implementation lol

grave rover
#

Fuyu

#

Ye

#

Your impl was the cleanest we had iirc

brazen geyser
#

there was a better one iirc

#

i thought it mightve been yours

#

it was really pretty, much cleaner

#

maybe im trippin

grave rover
#

I mean I wrote a bytecode transformer for doing this stuff

#

But that required an importhook to work globally

brazen geyser
#

human memory sucks

#

cant remember shit

#

but i digress

grave rover
#

You mostly solved it with using a custom exception

#

I think I might be able to do the same with this one

#

Gonna need a custom contextmanager tho

brazen geyser
#

ok maybe i was thinking of your suggestion to use with for the switch

zealous widget
#

i liked my version with the decorators and metaclass

earnest wing
#

That one is cute as well.

#

But metaclasses, frankly, frighten me more than they really should.

midnight bane
#

meta classes really arnt that bad tbh

#

they seem scary but once you actually make one its not too bad

formal sandal
#

Ah yes

#

Metaclass virginity

sick hound
#

hello

#

I'm trying to find the stupidest solution to:
"Print the word 'super' from string 'My dog is the most super duper boy'. Use string indexing."

#

currently I have
string='My dog is the most super duper boy'
super=string.find('super')
print(string[super:super+len('super')])

#

but that's not nearly convoluted enough

proper vault
#
string = 'My dog is the most super duper boy'
print(f'{string[string.find("super"):]:.{len("super")}}'
```is a bit more convoluted, but it is more a question of how much dead code are you willing to add
sick hound
#

true

proper vault
#

you can do something like

string.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')
```and a similar things with the `__getitem__`
sick hound
#

I like that, compact yet complex

bitter iris
#

hmm

#
for value in reversed(vars(__import__("builtins")).copy().values()):
    try:
        assert isinstance(value, type)
        value()
    except RuntimeError:
        for word in "My dog is the most super duper boy".split():
            if value.__name__ == word:
                print(word)
    except:
        pass
#

maybe something like this?

proper vault
#

that is clever

sick hound
#

what

#

I don't even

#

doesn't work for me in a jupyter notebook :/

#

but whatever it is, I love it

#

what would be the equivalent of
string.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')
but to get the len() of 'super'?

proper vault
#

replace that 'find' with 'len' and make that last call __call__('super')

sick hound
#

ah ok

#

I tried replacing the find, but not the other bit

#

hm, I still get KeyError: 'len'

proper vault
#

ah right, you have to do __len__

sick hound
#

ok I think I have it

#

down to a single, perfect line of code

#

print('My dog is the most super duper boy'['My dog is the most super duper boy'.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super'):'My dog is the most super duper boy'.__class__.__dict__.__getitem__.__call__('find').__call__(string, 'super')+sum(not out not in out for out in 'super')])

uneven sun
#

hey guys

snow beacon
#

You could assemble the slice using slice.

uneven sun
#

so i made an exe to automate some of my work, but my coworkers wanna use it too but they are on mac

#

is there a way i can bundle it all up into an app for them?

#

i dont wanan make them go into the terminal and install the libraries and stuff

snow beacon
#

This isn't the channel.

uneven sun
#

whoops

#

which channel is correct?

last locust
uneven sun
#

ahhhh

#

thats a cool setup thanks

sick hound
#

tell me more about this... slice

#

maybe I can replace the second index with it?

uneven sun
#

is slice different between c++ and python>? isnt that a negative thing to do?

#

when you put a derived object into a base object

#

im newish to python so im just asking cause i saw you guys discussing it

snow beacon
#

This is the channel for doing terrible things to Python.

vestal solstice
#
string = 'My dog is the most super duper boy'
string = [string[i:].startswith("super") for i in range(len(string))]
print(''.join("super"*i for i in string))
snow beacon
#

foo[a : b : c] = foo[slice(a, b, c)]

rustic flame
#

What is the most weirdest way to write b if the user enters a number but a otherwise? I have this but I think I can make it better```py
x = (lambda: input)()
if isinstance(x, int):
pass
else:
x = x((3 * '>') + ' ')
try:
x = int(x) ** 2
except:
print('a')
if isinstance(x, int):
print('b')

#

Actually I gtg so I'll check replies later

earnest wing
#
lambda x: print("ab"[all(47<ord(k)<58 for k in x)])

This is a cute way to do it.

#

I know isinstance might be shorter compared to the genexp, but I like the ord.

terse mortar
#

Y’all ever use the programming language “whitespace”?

#

It falls under python gore

frozen holly
#

white space is an abomination cos if you use like c or c++ or somthing then you can write 2 completely different programs in the same file, one in the whitespace and another in c++

snow beacon
#

Is it Python gore? It's not Python.

terse mortar
#

Well

#

Compared to python users it’s hell

#

So I still classify it as python gore

snow beacon
#

Is Java Python gore?

zealous widget
#

well, it's something gore

#

but i don't see how this esoteric language is related to python at all

terse mortar
#

Hmm

#

My reasoning made sense in my head

snow beacon
#

It's still a cool language, and I didn't realise it was made by Edwin Brady. Speaking of whitespace, what sort of programs can we write without using any?

earnest wing
#

No lambdas with arguments, no def blocks, and almost none of the keywords.

#

Semicolons will be helpful.

#

You can recurse with plain lambdas, as well as evaluate ternary conditions (as long as you use the right characters as padding—x if y else z can be converted to [x][0]if[y][0]else[z][0])

#

Input & output are fine, and you can easily push and pop values off a stack defined in the same scope.

#

Python with no whitespace is probably Turing-complete.

#

You can also exec("your$program§".replace("$",chr(32)).replace("§",chr(10)))

rugged sparrow
#

exec would be cheating tho

snow beacon
#

lambda*args:...

proper vault
#

Or lambda*,a,b,c:... and maybe lambda/,a,b,c:...

stark fable
#
factorial=lambda*b:(lambda*a:a[0](a[0]))(lambda*a:lambda*b:(lambda*c:lambda*d:a[0](a[0])(b[0]-1)(c[0])(c[0](d[0])))if[b[0]][0]else[lambda*a:lambda*a:a[0]][0])(b[0])(lambda*b:lambda*a:a[0](b[0](lambda*a:lambda*a:a[0])(b[0](lambda*a:lambda*b:a[0])(lambda*a:lambda*b:lambda*c:a[0](b[0])(b[0](c[0]))))(lambda*a:lambda*a:a[0]))(lambda*a:lambda*c:b[0](lambda*a:lambda*a:a[0])(a[0])(a[0](c[0]))))(lambda*a:a[0](lambda*a:a[0])(lambda*a:a[0]))(lambda*a:lambda*b:a[0])(lambda*a:a[0]+1)(0)```
#

python with no whitespace is definitely turing complete if you assume there's no recursion limit since you can use the lambda calculus ^

frozen holly
#

you code like a sith

last locust
#

What would be the dunder equivalent of converting a string to integer? E.g int("1").
For floats it’s float.__int()__ but doesn’t appear to be this for strings

formal sandal
#

I think __int__ is for numeric operations.

#

Like, if two objects don't define __add__, you can still add them if they have __int__ or something

proper vault
#
Init signature: int(self, /, *args, **kwargs)
Docstring:
int([x]) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is a number, return x.__int__().  For floating point
numbers, this truncates towards zero.

***If x is not a number or if base is given, then x must be a string***,
bytes, or bytearray instance representing an integer literal in the
given base.  The literal can be preceded by '+' or '-' and be surrounded
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
```int on strings is a special case
last locust
#

That doesn’t answer my question of how it actually works though? Ik strings are a ‘special case’, that’s why I’m asking. Does it maybe use int.frombytes or something?

snow beacon
#

I expect the int constructor just runs its own C code to parse strings.

edgy kelp
last locust
#

Ah, thank you

proper vault
edgy kelp
#

ah yes, but most of the internals it uses are in the from string

dull tartan
snow beacon
#

That library has this channel's implicit seal of approval, along with forbiddenfruit and that website for making code into a one-liner.

thin trout
#

Haha, that's so good

sharp void
#
factorial=lambda*b:(lambda*a:a[0](a[0]))(lambda*a:lambda*b:(lambda*c:lambda*d:a[0](a[0])(b[0]-1)(c[0])(c[0](d[0])))if[b[0]][0]else[lambda*a:lambda*a:a[0]][0])(b[0])(lambda*b:lambda*a:a[0](b[0](lambda*a:lambda*a:a[0])(b[0](lambda*a:lambda*b:a[0])(lambda*a:lambda*b:lambda*c:a[0](b[0])(b[0](c[0]))))(lambda*a:lambda*a:a[0]))(lambda*a:lambda*c:b[0](lambda*a:lambda*a:a[0])(a[0])(a[0](c[0]))))(lambda*a:a[0](lambda*a:a[0])(lambda*a:a[0]))(lambda*a:lambda*b:a[0])(lambda*a:a[0]+1)(0)```

Can someone explain to me how this works?

bitter iris
#

Here is a funny challange:

#

Python gives syntax warnings if you use a tuple in assert's test case

#
>>> assert (x, y)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
#

but there are some specific cases where this warning is omitted. Who wants to guess one of these weird cases (with the explanation)?

#

(assert's test should be a tuple and it should have at least 1 element)

formal sandal
#

!e

assert (1, 2)
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
formal sandal
#

I have no explanation

#

I am confused

bitter iris
#

actually the good part is the explanation

formal sandal
#

!e

import dis
def f():
    assert (1, 2)
dis.dis(f)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 |   3           0 LOAD_CONST               1 ((1, 2))
002 |               2 POP_JUMP_IF_TRUE         8
003 |               4 LOAD_GLOBAL              0 (AssertionError)
004 |               6 RAISE_VARARGS            1
005 |         >>    8 LOAD_CONST               0 (None)
006 |              10 RETURN_VALUE
formal sandal
#

!e

import dis
def g():
    assert (x, y)
dis.dis(g)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:3: SyntaxWarning: assertion is always true, perhaps remove parentheses?
002 |   3           0 LOAD_GLOBAL              0 (x)
003 |               2 LOAD_GLOBAL              1 (y)
004 |               4 BUILD_TUPLE              2
005 |               6 POP_JUMP_IF_TRUE        12
006 |               8 LOAD_GLOBAL              2 (AssertionError)
007 |              10 RAISE_VARARGS            1
008 |         >>   12 LOAD_CONST               0 (None)
009 |              14 RETURN_VALUE
formal sandal
#

Maybe it has something to do with BUILD_TUPLE instruction

#

Because in the first case, it's just loading some constant

bitter iris
#

Maybe it has something to do with BUILD_TUPLE instruction
@formal sandal yep

proper vault
#

!e

assert ([],)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

<string>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
thin trout
#

SyntaxWarning are only generated at compile time, right, so I guess it has to do something with that?

bitter iris
#

yep

thin trout
#

So if the tuple can be constructed at compile time and stored as a constant, it will not raise the warning

proper vault
#

!e

def a():
    assert (a,)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

<string>:2: SyntaxWarning: assertion is always true, perhaps remove parentheses?
proper vault
#

so it just checks for BUILD_TUPLE, rather than checking the type in LOAD_CONST, probably because it is non-trivial to figure out if it is the value of LOAD_CONST is exactly the value passed into the assert

bitter iris
#

Pretty close

gentle pagoda
#

I doubt this is possible, but maybe: can i catch a NameError and replace it with something? so x + 5 gets replaced with something() + 5. all of the exception hooks ive seen dont allow you to return, so i doubt its possible :(

proper vault
#

you mean it would retroactively use a different value for the name?

#

so something like

try:
    print(some_name_that_is_not_defined * 3)
except NameError as e:
    e.use_instead(9)
```would print 27?
#

not real code

#

pretty sure this is not reasonably possible, AFAIK only LISP dialects are capable of this level of self correction

gentle pagoda
#

ah okay

#

i might try modifying the ast, that feels messy though

#

id rather do it pure python

bitter iris
#

i might try modifying the ast, that feels messy though
@gentle pagoda actually it is kind a easy, I once write project called pepallow which would re-write some names and suppresses the original errors (it is a very old piece of code, even older than the git date, just to show as an example)

github.com/isidentical-archive/pepallow/blob/5983074f668f6b85677506e117976d2c2fa751ed/pepallow/peps/p313.py#L13

github.com/isidentical-archive/pepallow/blob/5983074f668f6b85677506e117976d2c2fa751ed/pepallow/allow.py#L38-L46

gentle pagoda
#

oh thats cool, ill try it

#

thanks :)

mystic escarp
#

Hello! Well am a novice in python. I have a project that demands me to create an app so I decided to go in for tic tac toe. Am at the level of making the buttons work now i.e the function I need to make the buttons work properly. Am using classes just to note. Need some help please.

pine edge
#

this channel is not for that, sorry

bitter iris
#

<@&267629731250176001>

vague gust
#

!ban 287734159546515456 spam

night quarryBOT
#

:x: User is already permanently banned (#7813).

vague gust
#

ah

hollow patrol
#

Do you want a generator expression?

#

(x + 1 for x in seq)

#

Here's an esoteric version.

#

(lambda: [(yield x + 1) for x in seq])

formal sandal
#

Won't work in 3.8

marsh void
#

yield in lambda tf

brisk zenith
#

yeah that's a thing

proper vault
#
SyntaxError: 'yield' inside list comprehension
brisk zenith
#

yeah remove the list brackets

#

then it'll do the do

hollow patrol
#

But then we're using generator expressions

#

That's the whole thing we're trying to avoid

#

Wait, and we can't use yield in generator expressions?

proper vault
#

you can do

(lambda f, i: f(f, i))(lambda f, i: (yield from (lambda n: ((yield n+1), (yield from f(f, i)))if n is not None else (yield from []))(next(i, None))), iter(seq))
hollow patrol
#

I also got ```python
import('itertools').chain(*[
(lambda i: (yield i))(i)
for i in range(3)
])

#

Wait

#

You're using a y-combinator

#

That works too

formal sandal
#

!e

seq = [1, 2, 3, 4, 5]
x = (lambda f, i: f(f, i))(lambda f, i: (yield from (lambda n: ((yield n+1), (yield from f(f, i)))if n is not None else (yield from []))(next(i, None))), iter(seq))
print([*x])
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[2, 3, 4, 5, 6]
formal sandal
#

oh

#

it's how it's supposed to work

limpid crest
#

respect to people who are into esoteric python

potent comet
#

Yield was prohibited in list comprehensions, since it does weird things - you get a generator not a list (exposing a sorta implementation detail), the result of send() is put in the list, then the list itself comes out of the StopIteration exception...

hollow patrol
#

I feel like yield could work just fine

#

[(yield i) for i in range(3)] is just any part of a function

#

(yield i) gets evaluated to whatever send gives

#

and the result is the value of each send

formal sandal
#

the problem is that comprehensions are implemented as functions.

thin trout
#

It doesn't really make sense IMO to use yield in list comp since we have gen expr anyway

viral gyro
#

What does esoteric mean exactly? Not sure i get what this channel is about

edgy kelp
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness

viral gyro
#

Ok i dont know what any of those things are, just gonna read you guys

edgy kelp
#

Golfing is making the code as short as possible for example

viral gyro
#

Oh i do like that

#

Great, will google the rest, thx

frozen holly
#

its basically python that is supposed to make you vomit when you see it, but also works

brisk zenith
#

yeah, we just fuck around with python because it's fun

hollow patrol
#

@thin trout Even then, us esoteric python users would like the feature

#

!e

__import__('itertools').chain(*[
  (lambda i: (yield i))(i)
  for i in range(3)
])
night quarryBOT
#

@hollow patrol :warning: Your eval job has completed with return code 0.

[No output]
hollow patrol
#

But it's unrealistic

thin trout
#

it doesn't make any freakin sense haha

hollow patrol
#

That's the point of this channel

#

In esoteric Python, nothing ever has to make sense.

thin trout
#

I mean, things here have a sense (most of the time)

hollow patrol
#

!e

print(*__import__('itertools').chain(*[
  (lambda i: (yield i))(i)
  for i in range(3)
]))
night quarryBOT
#

@hollow patrol :white_check_mark: Your eval job has completed with return code 0.

0 1 2
hollow patrol
#

and maybe

#

a lot of times it doesn't

#

I made a Python one-liner, it doesn't make sense.

minor palm
#

!e

f=lambda x:[[y for j,y in enumerate(set(x))if(i>>j)&1]for i in range(2**len(set(x)))];print(f([10,9,1,10,9,1,1,1,10,9,7]))```
night quarryBOT
#

@minor palm :white_check_mark: Your eval job has completed with return code 0.

[[], [9], [10], [9, 10], [1], [9, 1], [10, 1], [9, 10, 1], [7], [9, 7], [10, 7], [9, 10, 7], [1, 7], [9, 1, 7], [10, 1, 7], [9, 10, 1, 7]]
sick hound
#

wh

#

what is that

proper vault
#

I think it finds all subsets, though in a slightly odd way

snow beacon
#

Oh, I see. It might be better to use sets instead of lists.

sick hound
#

heavy breathing

#

g a h

viral gyro
#

Import GlobalCommunications
print("covid-19 is over")

#

(?

snow beacon
#

I think that would be a syntax error.

earnest wing
#

There's also a logic error.

marsh void
#

Import is uppercase

#

and also unused

thin trout
#

I made a Python one-liner, it doesn't make sense.
@hollow patrol it has a sense, its sense is to be in one line :P

hollow patrol
#

huh

thin trout
#

So TIL that .__call__ attributes have a .__call__ attribute that's just silly haha

proper vault
#

indeed they do

brisk zenith
#

well of course they do. that's what makes the () on the end of .__call__() work haha

#

it's like how .__str__ has a .__str__ attribute.

#

that's the power of descriptors which i'm yet to wrap my mind around.

thin trout
#

!e

print.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__('Hello call!')```
night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

Hello call!
thin trout
#

That's so silly haha

brisk zenith
#

but it makes sense though

#

__call__ is callable, which means it needs a __call__ method.

thin trout
#

Yes, but my docstring scrapper doesn't like it haha

grizzled cloak
#

but what does __call__ call?

#

it cant just call itself lol

thin trout
#

I wonder how that actually work, are the __call__ generated by the parser?

brisk zenith
#

i think the additional __call__ methods are generated on the fly because of descriptor magic.

thin trout
#

Yeah, if you want to call the __call__ you have to call its __call__? Haha

brisk zenith
#

but when you actually call it, the internals don't need to refer to that extra __call__ method

thin trout
#

!e

print(type(print.__call__))```
night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

<class 'method-wrapper'>
thin trout
#

Yeaaahh

brisk zenith
#
>>> class A:
...     def __str__(self): pass
... 
>>> A.__str__
<function A.__str__ at 0x7fa3298480d0>
>>> A.__str__.__str__
<method-wrapper '__str__' of function object at 0x7fa3298480d0>
>>> 
#

these method-wrappers won't have anything you're interested in for your docstring thing

proper vault
#

!e

print(print.__call__ is print.__call__.__call__, print.__call__.__call__ is print.__call__.__call__.__call__)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

False False
thin trout
#

Yeah, I could ignore those

brisk zenith
#

well, you should ignore those.

#

they're not user-generated.

thin trout
#

A dir() parameter to inshore the compiler-generated one's would be nice, though

brisk zenith
#

they're not compiler generated, i believe they're generated by the descriptors at runtime or something

#

but yeah, i know what you mean.

thin trout
#

Is there a dis madness to see how they are generated without looking at the source?

brisk zenith
#

i doubt it since i reckon it's all transparent to the bytecode.

#

well, not transparent

#

but invisible

#

the bytecode probably doesn't have a clue whether they're user-defined or not.

#

you could use the types library to your advantage though.

#

!e ```py
from types import MethodWrapperType

class Example:
def str(self):
return "this is an example!"

e = Example()
once = e.str
twice = e.str.str
trice = e.str.str.str

print("once:", isinstance(once, MethodWrapperType))
print("twice:", isinstance(twice, MethodWrapperType))
print("thrice:", isinstance(thrice, MethodWrapperType))

night quarryBOT
#

@brisk zenith :x: Your eval job has completed with return code 1.

001 | once: False
002 | twice: True
003 | Traceback (most recent call last):
004 |   File "<string>", line 14, in <module>
005 | NameError: name 'thrice' is not defined
brisk zenith
#

fucking

#

trice!

#

!e ```py
from types import MethodWrapperType

class Example:
def str(self):
return "this is an example!"

e = Example()
once = e.str
twice = e.str.str
thrice = e.str.str.str

print("once:", isinstance(once, MethodWrapperType))
print("twice:", isinstance(twice, MethodWrapperType))
print("thrice:", isinstance(thrice, MethodWrapperType))

night quarryBOT
#

@brisk zenith :white_check_mark: Your eval job has completed with return code 0.

001 | once: False
002 | twice: True
003 | thrice: True
brisk zenith
#

@thin trout if the attribute is an instance of this mystical MethodWrapperType then you should ignore it. there'll be other similar types to look out for too, but you'll just have to experiment to see what types from the types module you should or shouldn't include in your docstring scraper thing.

thin trout
#

blobthinkingdown hmm interesting thanks!

#

You can edit your eval btw if you made a typo :>

brisk zenith
#

oh can you

#

how nice.

narrow ridge
#

what is esoteric python

eager pond
#

The abnormal or weird or unknown sides of the language

narrow ridge
#

hmmm

#

i see yeah

hollow patrol
#

I think __call__ depends on its actual function

#

since when I used a while loop on it

#

or some sort of loop

#

!e

def f():
  print(5)
for i in range(5000):
  f = f.__call__
f() #throws a recursion error I believe
night quarryBOT
#

@hollow patrol :white_check_mark: Your eval job has completed with return code 0.

5
hollow patrol
#

!e

def f():
  print(5)
for i in range(105000):
  f = f.__call__
f() #throws a recursion error I believe
night quarryBOT
#

@hollow patrol :white_check_mark: Your eval job has completed with return code 0.

5
hollow patrol
#

!e

def f():
  print(5)
for i in range(5000000):
  f = f.__call__
f() #throws a recursion error I believe
night quarryBOT
#

@hollow patrol :warning: Your eval job timed out or ran out of memory.

[No output]
hollow patrol
#

I thought it would throw an error

brisk zenith
#

i think descriptor magic makes any amount of .__call__s stringed together just call the original function directly, without having to call each method in the chain

mortal matrix
#

hello beatiful people here, i'm new here and i was wondering why some channels are named after chemical stuff

brisk zenith
#

each name is quite different from the others and there are plenty to go around.

#

but this also isn't the right channel to ask server-related questions ^^

mortal matrix
#

okay. thank you

#

how long have you been using python ?

brisk zenith
#

idk, a few years by now.

sage olive
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

queen oriole
#

soo I'm editing a photoshop file using win32com.client

#

PS = win32com.client.Dispatch("Photoshop.Application")

#

and I used a page with some simple guides to do it so far but it doesn't tell me everything, does anyone know where I can find a full docs ofr this

hollow patrol
#

not sure this is the channel for that, G-Unit

midnight bane
#

!e ```py
def my_function():
print("hi!")

exec(f"my_function{'.call' * 2991}()")

night quarryBOT
#

@midnight bane :white_check_mark: Your eval job has completed with return code 0.

hi!
midnight bane
#

!e ```py
def my_function():
print("hi!")

exec(f"my_function{'.call' * 2992}()")

night quarryBOT
#

@midnight bane :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | RecursionError: maximum recursion depth exceeded during compilation
potent comet
#

That's from the fact that there's so many nested attribute calls.

#

Break it up into two lines.

stark fable
#

!e ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((

night quarryBOT
#

@stark fable :x: Your eval job has completed with return code 1.

001 | s_push: parser stack overflow
002 | MemoryError
formal sandal
#

yep

#

one more reason to use pypy, lol

#

Maybe it will be fixed in the new parser, though.

#

I guess it's a bit off topic, but maybe we can do something similar in Python?
https://github.com/Battelle/movfuscator
It's a C compiler for x86 architecture that produces machine code containing only mov instructions.

#

I don't know if Python has this sort of robust instuction (or 2-3 instructions)

#

Maybe our attempts at reimplementing stdlib in pure python weren't in vain!

#

(I mean, in a warped and crazy way of not in vain)

brisk zenith
#

@formal sandal i think something like that could be quite doable with a very very limited set of bytecode instructions

#

i think something that converts bytecode made by cpython's standard compiler into the limited bytecode version would be a good first step, perhaps.

#

i imagine the movfuscator uses movs to change the program counter register for dealing with control flow, but i don't imagine anything in python bytecode can do that beyond the dedicated instructions

#

(i haven't actually looked at the movfuscator, but i'm just going by what my intuition thinks)

last locust
#
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [n for n,e in zip(x,map(lambda y:y%2==0,x)) if n and e]
print(converter(nums))
```is there a better/faster way than my 'converter' variable to get all numbers in a list that are even and not 0?
#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [n for n,e in zip(x,map(lambda y:y%2==0,x)) if n and e]
return converter(nums)

import timeit
print(timeit.timeit(m1))

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

5.766138376668096
last locust
#

Ultimately trying to get it under 5secs, but every little helps

edgy kelp
#

that seems overly complicated

thin trout
#

that seems overly complicated
@edgy kelp Isn't that the whole channel purpose?

last locust
#

Wanted to use map, and adding the zip seemed the easiest way to implement that

rugged sparrow
#
converter = lambda x:[*filter(lambda n:n and n%2==0,x)]
``` @last locust this works
edgy kelp
#

if you want to use map then you can just drop the zip and return the original value in the lambda

last locust
#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: [*filter(lambda n:n and n%2==0,x)]
return converter(nums)

import timeit
print(timeit.timeit(m1))

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

4.172575471922755
last locust
#

Nice 👍

#

Forgot about filter

#

And yea true @edgy kelp. Honestly just messing around with different methods

rugged sparrow
#
converter = lambda x:[n for n in x if n and n%2==0]
#

works

bitter iris
#

one more reason to use pypy, lol
@formal sandal or wait the new PEG parser :)

rugged sparrow
#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x:[n for n in x if n and n%2==0]
return converter(nums)

import timeit
print(timeit.timeit(m1))```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

2.4834218118339777
rugged sparrow
#

@last locust ^

last locust
#

Yea that's the obvious one

#

Was trying to find more 'obscure' methods

rugged sparrow
#

ahh ok

last locust
#

Really like your filter one though

brisk zenith
#

you want obscure? give me a moment.

rugged sparrow
#
converter = lambda x:[n for n in x if f'{(n if n else 1)/2}'[-1]=='0']```
#

@last locust ^

#

checks if the last digit of a float is 0 and replaces n with 1 if its falsy (0)

last locust
#

Yea that's definitely obscure :p

#

Probably pretty fast too

formal sandal
#

Is there some example of a list comprehension which is orders of magnitude more obscure than a composition of higher-order functions?

last locust
#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x:[n for n in x if f"{(n if n else 1)/2}"[-1]=="0"]
return converter(nums)

import timeit
print(timeit.timeit(m1))```

night quarryBOT
#

@last locust :warning: Your eval job timed out or ran out of memory.

[No output]
last locust
#

🤔

formal sandal
#

Pretty fast

rugged sparrow
#

Lmao it was way slow

last locust
#

It's about 13sec o-o

formal sandal
#

I'm confused

last locust
#

Same lol

formal sandal
#

!e

def m1():
    nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
    converter = lambda x:[n for n in x if f"{(n if n else 1)/2}"[-1]=="0"]
    return converter(nums)

print(m1())
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[2, 2, 4, 2, 4]
formal sandal
#

Oh

#

Timeit probably runs it a million times or something

last locust
#

timeit.timeit runs it 1mil times

#

Yea

brisk zenith
#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: list(filter(range(2,max(x)+1,2).contains,x))
return converter(nums)

import timeit
print(timeit.timeit(m1))

#

not efficient, but funky.

#

hold on, lemme retry

#

!e ```py
def m1():
nums = [0,1,2,3,0,0,2,3,4,0,2,5,3,3,4,1,0]
converter = lambda x: list(filter(range(2,max(x)+1,2).contains,x))
return converter(nums)

import timeit
print(timeit.timeit(m1))

night quarryBOT
#

@brisk zenith :white_check_mark: Your eval job has completed with return code 0.

5.5626190751791
last locust
#

Nice

small crypt
#
app
  app.py
  tenant1
    __init__.py
    blueprints.py

init.py

with open("tenant1/config.json) as file:
  config = json.loads(file.load) 

how do i let blueprints.py read the config variable

#

i've tried from tenant1 import config but it didn't work

grizzled cloak
#

just read the file again

small crypt
#

thats inefficient

small crypt
#

nevermind i fixed it

#

im just retarded

stark fable
#

i imagine the movfuscator uses movs to change the program counter register for dealing with control flow, but i don't imagine anything in python bytecode can do that beyond the dedicated instructions
iirc what it actually does is it's a series of movs and then one unconditional jump back to the beginning of the program

#

one unconditional jump to the beginning, stopping the program is done by reading from address 0

brisk zenith
#

haha, that's how all of my programs stop too 🙃

hollow patrol
#

I still want to learn how to make a function that maintains its parent's scope

#

Without any nonlocal, local, or global definitions

brisk zenith
#

you'd have to modify the function's __code__ object in some way.

hollow patrol
#

yeah but I'm not sure how

#

I can edit the co_code but the rest of the function won't line up

brisk zenith
#

i'm poking around at it right now

hollow patrol
#

by the way

brisk zenith
#

i don't think co_code would be the first place i'd go for

hollow patrol
#

if you manage to do this, you can complete my onelinifier for python

#

since allowing try-except loops in the parent scope would finish this

brisk zenith
#

modifying stuff like co_names and attributes like that would be my first step

quiet niche
#

like, retain it

hollow patrol
#

alright

#

I'm not good with bytecode

quiet niche
#

you already have parent's scope?

#

and you just want to write it into the current function?

hollow patrol
#

I want to people to set variables in the parent scope from a lower scope

brisk zenith
#

is this just the first parent?

hollow patrol
#

the parent right above

brisk zenith
#

okay cool

hollow patrol
#

and I want it to work for nested parents

quiet niche
#

so you only have control of the parent, and arbitrary child

hollow patrol
#
def x():
  z = 2
  def y():
    nonlocal z
    z = 4
  y()
x()
#

but in lambdas

quiet niche
#

so essentially you want it to make everything inside it nonlocal automagically

#

or the inverse, where the child reaches up

hollow patrol
#

yep

quiet niche
#

the latter should be fairly simple

#

but the former idk

hollow patrol
#

basically

quiet niche
#

w..which one is yep

hollow patrol
#

everything is a nonlocal

quiet niche
#

ah

hollow patrol
#

the child edits the parent's scope

#

not the parent edits the child's scope

brisk zenith
#

i think it would be reasonable to have it accessible via something like this: py def outer(): x = 1 @use_parent_scope def inner(): x = 3 return inner() outer()
that way the inner function's __code__ object can be modified every time it is created (since inner doesn't exist until it is defined at each outer call).

hollow patrol
#

yep

#

except it'll be lambdas

#

and use_parent_scope will be a function call

quiet niche
#

actually

brisk zenith
#

naturally :D

hollow patrol
#

but you don't have to worry about that

quiet niche
#

what do you want to use this for

hollow patrol
#

for my one-lineifier

quiet niche
#

what one-lineifier

hollow patrol
#

which one-lines Python 3.8 code

quiet niche
#

also maybe ast is the way to go, honestly

#

like

#

arbitrary python 3.8 code?

hollow patrol
#

It already uses ast

#

and yes

quiet niche
#

like in string form or uh

#

it.. turns it into a python script that's one line?

hollow patrol
#

yes

#

it already works for the most part

#

with functions, for loops, while loops, if statements, classes, etc

#

even generators

quiet niche
#

does exec(file.replace("something","\n")) count

hollow patrol
#

nope

#

no executing

#

no evaluating

quiet niche
#

you can do it in python 2

#

i know that

hollow patrol
#
while True:
    for i in range(3):
        print(i)

is converted to

(
    (
        do_while := (
            lambda cond, c=0: (
                (((yield c), (yield from do_while(cond, (c + 1)))) if cond() else None),
            )
        )
    ),
    [
        ([(print(i), None)[(-1)] for i in range(3)], None)[(-1)]
        for _ in do_while((lambda: True))
    ],
    None,
)[(-1)]
quiet niche
#

i would probably say that it's probably easier to tweak the lambda calculus than muck around with the frame

hollow patrol
#

so what

rugged sparrow
#

i still think you should just handle scoping manually

hollow patrol
#

probably, and it would be easier

#

but using the parent scope would be isolated to one part of the code

#

and it would make the rest much cleaner

quiet niche
#

the python 2 onelineifier is basically just a lambda calculus-ified version of each bit of python syntax

hollow patrol
#

x := 3 is much cleaner than d.__setitem__('x', 3)

rugged sparrow
#

not if it requires func object modifications

quiet niche
#

how dya intend to do try: except: blocks

hollow patrol
#

with contextlib

rugged sparrow
#

ContextDecorators @quiet niche

quiet niche
#

ah ye

#

what do you need the scoping to implement?

hollow patrol
#

I need it to implement every python variable thing

#

so instead of f(1, 2, 3, 4)

#

it's f({'x': 1, 'y': 2, 'a': 3, 'b': 4})

#

except it's merged with the original scope

#

and if the outer scope has a variable, this one won't see it

#

and etc

quiet niche
#

replace references to variables with instance variables of a big honking singleton bloblul

#

regardless, i think python's lexical scoping rules make it essentially impossible without cheating in some form of source-code-rewriting

hollow patrol
#

that's why we have to modify bytecode

quiet niche
#

if you're modifying bytecode you might as well just do source code rewriting in python directly and save yourself the trouble bloblul

#

rebuilding functions from disassembled objects OTF is a wacky game

brisk zenith
#

bytecode modifications are probably necessary, yes. you'll have to change co_varnames, co_freevars, and probably a couple more attributes for both the inner and outer functions' __code__ object, and then modify the bytecode itself to reflect those changes (but at least then you're not dealing with misaligned jump destinations, just directly swapping out LOAD instructions with other LOAD instructions with different indices for the different variable types)

hollow patrol
#

I'm not sure how to do that though

brisk zenith
#

well i'm not either to be honest haha

#

i've been comparing these attributes between functions with no scope sharing, and then the exact same thing with everything shared from the parent to the child through nonlocal

hollow patrol
#

then I guess my limited one-liner will have to do

#

if I can't

quiet niche
#

actually i bet pycell_set could do something

#

you probably roughly want cells

#

but down that path lies madness

hollow patrol
#

I sort of want it to be implementation-independent

quiet niche
#

hm

#

just pretend that cpython is the only kind that exists

hollow patrol
#

no

#

@rugged sparrow I saw you

rugged sparrow
#

heh

hollow patrol
#

heh

quiet niche
#

just wait until python 4 when we dont have language intrinsics anymore : ^ )

#

switch to ruby

#

imagine not being able to overwrite variable assignment penSivvwobbliy

hollow patrol
#

I'm being serious 😆

#

generally though, how would I do it

#

also, can I yield in the higher function too?

quiet niche
#

you have (cross-platform, doesn't require cheating, doesnt require incredibly bytecode expertise), probably pick 2

brisk zenith
#

if you want to modify bytecode, here is what you need:

by making everything nonlocal, it seems like the parent moves all of its co_varnames into its co_cellvars, and any variable name which is present in the parent's new co_cellvars is moved into the child's co_freevars, with the same variable names being removed from the child's co_varnames if present. i haven't checked what happens with co_names yet. i actually don't know what that contains, really.

then you just need to turn all of the LOAD_FAST calls in the bytecode into the equivalent LOAD_CLOSURE instructions, as well as probably some other similar changes that i'm yet to figure out.

bear in mind that bytecode is a cpython implementation detail.

hollow patrol
#

oh well, I guess I'll stick with bytecode then

rugged sparrow
#

im excited for this in 3.9 https://www.python.org/dev/peps/pep-0554/

hollow patrol
#

@brisk zenith how can I yield in the higher function?

quiet niche
#

yeah bytecode is cheat

rugged sparrow
#

cause itll prob let us mod the current interpreter

quiet niche
#

ah yes

brisk zenith
#

!pep 554

night quarryBOT
#
**PEP 554 - Multiple Interpreters in the Stdlib**
Status

Draft

Python-Version

3.10

Created

2017-09-05

Type

Standards Track

quiet niche
#

good ol pep 554

brisk zenith
#

be civil, chilaxan

#

:D

rugged sparrow
#

but i want to implement multiple languages in my python

brisk zenith
#

@hollow patrol can you give an example of what you're trying to do?

hollow patrol
#
try:
  yield 1
except:
  pass
#

wait

#

nvm

brisk zenith
#

haha okay

hollow patrol
#

but yeah

#

that example

#

I'd like to do that in lambdas

#

in the current scope

brisk zenith
#

i'm not too sure about how you'd do that, really.

hollow patrol
#

same

brisk zenith
#

oh fun, cpython isn't happy when you try to add more free variables to a closure.

hollow patrol
#

yeah, lots of fun likely

#

well, on another topic, I made an iterator class and made its methods get added to every python object

#
for c, (before, current, after) in range(10).context(count = 2).enumerate():
  print(c, '-', before, current, after)

Output

0 - 0 1 2
1 - 1 2 3
2 - 2 3 4
3 - 3 4 5
4 - 4 5 6
5 - 5 6 7
6 - 6 7 8
7 - 7 8 9
brisk zenith
#

i believe adding more free variables to a function would require one of two things:

  1. overwriting the tuple's length value in memory using ctypes. this would be likely to cause some sort of memory violation or buffer overflow somewhere along the line.
  2. changing the co_freevars pointer value in the struct to make it refer to the new appropriately-sized tuple. this could cause memory leaks and probably memory violations, as well as potential dangling references in the interpreter.

tl;dr: don't do. it bad.

hollow patrol
#

well, we don't have to change it

#

we could make a new function with the properties

brisk zenith
#

that's true enough.

#

i'll consider working on that soon then, i'm tired.

#

have you ever seen a code object being constructed in python code? it's terrifying.

hollow patrol
#

nope I haven't, but I believe you

brisk zenith
#

that _patch_code function would come in handy for this.

potent comet
#

As of Python 3.8, CodeType now has a replace() method for copying and changing just some attributes.

brisk zenith
#

yep, but that produces an error when trying to replace co_freevars with a tuple which is longer or shorter than the previous

rugged sparrow
#

@brisk zenith if you replace everything else that freevars depends on at the same call it doesn't error afaik

potent comet
#

It doesn't look like it should?

brisk zenith
#

the C code behind it compares the tuples sizes with the python api

hollow patrol
#

One time I made something called javar in Python

#

Basically it makes your code require a single class, and it is given attribute security

hollow patrol
#

I still like the idea of a switch case in Python

#
with switch(3):
  with case(1):
    print(5)
  with case(2):
    print(4)
  with case(3):
    print(3)
  with case(ELSE):
    print('none')
#

I saw discussion about it a few days/weeks ago

#

Did anyone finish it?

marsh void
#

why with case(ELSE), I would do with default()

#

I don't remember what strategy was used though

hollow patrol
#

I'm not sure

#

why I used case(ELSE)

#

I was just randomly showing an example

marsh totem
#

@hollow patrol have you tried using dicts instead?

hollow patrol
#

that doesn't work with function bodies as cleanly

marsh totem
#

mmm, I don't fully follow. I see the example above as

ARG = {1: 5, 2: 4, 3: 3}
print(ARG.get(3, "none"))
hollow patrol
#

@marsh totem that's one example

#
def f():
  with switch(3):
    with case(1):
      print(5)
    with case(2):
      print(4)
      raise (yield 2)
    with case(3):
      print(3)
    with case(ELSE):
      print('none')
      out = 5 + 4
      while out < 20:
        out += 1
        for i in range(out): 
          print(i)
  print(out)
#

I'm not so sure you can one-line this

marsh totem
#

gotcha

hollow patrol
#

I get your point

#

it's just for more complex switch-cases, you can't one-line it

marsh totem
#

yeah, you might need to extract stuff into helper functions

#

so that you end with something like:

def default():
    #long function

ARG = {1: foo(5), 2: bar(4), 3: baz(3)}
ARG.get(x, default())
hollow patrol
#

how about each of those

#

I don't want to do ARG = {1: f1, 2: f2, 3: f3} ARG.get(x, default)()

marsh totem
#

I think that from what you just posted, that's the way to go

#

I'v used that form before, with nicer names

#

like

processors = {1: f1, 2: f2, 3: f3}
processor = processors.get(x, default)
result = processor()```
#

at that point I think it's a matter of taste 🙂

earnest wing
#

Unrelated, but here's a fun little thing I made:

In [1]: for i in 0-to-10-by-2:
   ...:     print(i)
   ...:
0
2
4
6
8
In [2]:
#

Also:

In [3]: for i in 0-to:
   ...:    if i > 100:
   ...:        break
   ...:    print(i)
   ...:
#

:^)

#

You know, just in case you wanted more natural-language syntax in python. (See: word for word in words if word not in swears)

snow beacon
#

All I have to say is "word."

marsh totem
#

is it a wrapper around range, or something else?

snow beacon
#

Presumably it couldn't do an infinite range.

#

The to suggests it's making its own iterator.

earnest wing
#

It's a custom implementation of range to allow for infinite iteration.

#

The iterator portion is trivial, though. Most of the code is in __sub__ and __rsub__ for the syntax trickery.

#

Ignore the inconsistency between positional args and kwargs.

#

I wonder whether other builtins could be "naturalized" like so.

#

len(x) <=> count-of-x

marsh totem
#

I guess that if you run it through a code formatter it's transforming it to 0 - to - 10 - by - 2

earnest wing
#

Yes, hence the overridden __sub__.

#

You could probably also make use of __contains__ to make even more natural-sounding syntax.
n in binary <=> bin(n)

hollow patrol
#

That's interesting

rare yarrow
#

Unrelated, but here's a fun little thing I made:

In [1]: for i in 0-to-10-by-2:
   ...:     print(i)
   ...:
0
2
4
6
8
In [2]:

@earnest wing is that valid python syntax? Or some sort of preprocessor?

#

I think I see how that could be done with operator overloading but that's still quite cool!

#

Would generator-by-2 work on any generator?

earnest wing
#

The current implementation is pretty limited (https://mystb.in/raw/fofolasado) but surely that could be possible (see the __rsub__ section with _state == 1)

rare yarrow
#

Quick question, how does python know whether to use a.__sub__(b) or b.__rsub__(a) for a-b?

earnest wing
#

If __sub__ returns NotImplemented, the interpreter tries __rsub__.

#

The same for any __r*__ operation.

rare yarrow
#

Ah ok

#

I never knew r* operations even existed until now

#

TIL

#

thanks 😊

earnest wing
#

Yeah, it means that __rlshift__() is in fact a valid special method :^)

zealous widget
#

have overloaded that method a few times even

formal sandal
#

also __rrshift__

thin trout
#

Would you know a way to override the list type returned by [] to a custom one?

#

From what I can see, it will always use the BUILD_LIST instruction

formal sandal
#

Well, you could rewrite bytecode...

#

BUILD_LIST -> BUILD_LIST + (call __list_builder__)

#

maybe you could do some crazy stuff with ctypes?

thin trout
#

Hmm, how would that work, rewriting the bytecode ?

formal sandal
#

You'd have to apply a decorator to every function, though.

#

I'm not sure it would work if you change it globally, since pure-python stdlib modules might break

formal sandal
#

Statically typed shell

#

I like it

thin trout
#

Hmm blobthinkingdown

#

And if the new list implements the whole legacy list functions, is there at least a way to patch the bytecode globally

rugged sparrow
#

Depending on the interpreter implementation you might be able to patch compile

sick hound
polar lagoon
#

@sick hound

#

Is it okay to discuss in here?

sick hound
#

why would you pick this channel? 😛

stark fable
#

this channel is for discussion of doing really really weird things with python that you would never actually use in practice

#

like this implementation of factorial py factorial = lambda b:(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(b)(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a)(lambda a:a+1)(0)

rare yarrow
#

@stark fable holy fucking shit

#

can you explain how that works?

stark fable
#

the basic idea is that it's using church numerals, which is a way of representing numbers as functions

rare yarrow
#

ah so it's lambda calculus basically

stark fable
#

yes

#

lambda calculus implementation of factorial, with some stuff around it to convert to and from python integers

rare yarrow
#

do you pass it an integer or church numeral?

stark fable
#

you pass an integer

rare yarrow
#

oh so it converts it to a church numeral and back?

#

cool

stark fable
#

(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a) converts from an integer to a church numeral

#

the (lambda a:a+1)(0) at the end converts it back

rare yarrow
#

ok I can kind of see how that works

#

this is the textbook definition of esoteric lmfao

stark fable
#

lambda a:a(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a) is the actual factorial part, which operates on church numerals

#

though actually it might not appear in that form in the finished thing since i reduced it a bit

rare yarrow
#

that part I have no clue how it works

stark fable
#

well it's made of a lot of separate things

rare yarrow
#

I feel like an explanation will fly over my head tho tbh

stark fable
#

zero is lambda a:lambda a:a, and one is lambda a:a

#

add_one is lambda a:lambda b:lambda c:a(b)(b(c))

rare yarrow
#

hold up shouldn't one be lambda a:lambda b:a(b)?

stark fable
#

lambda a:lambda b:a(b) is the same as lambda a:a

rare yarrow
#

wait nvm that's the same as lambda a:a right

stark fable
#

add is lambda a:a(add_one) which becomes lambda a:a(lambda a:lambda b:lambda c:a(b)(b(c))) when you substitute in add_one

rare yarrow
#

I don't get add_one

#

(I do get add tho)

#

why does add_one work?

stark fable
#

a is the number you're adding 1 to

#

b is the function that's repeated

#

c is the initial argument

#

you do a(b) to repeat b a times

#

and then you apply one extra b

#

to c

rare yarrow
#

ok I may be misunderstanding the purpose of add_one

stark fable
#

it adds one to a church numeral

rare yarrow
#

is add_one(1) == 2 and add_one(2) == 3, etc?

#

or how do u call it?

stark fable
#

yes, it adds one

rare yarrow
#

oh wait I see!

stark fable
#

although it's with church numerals, not python integers

rare yarrow
#

because add_one needs to behave like a number

#

right

stark fable
#

well add_one isn't a number, but the thing it returns is

rare yarrow
#

yea that's what I meant

#

after invoking it once

#

then it needs to be a church numeral

stark fable
#

yep

#

anyway, mult is lambda a:lambda b:b(add(a))(zero)

rare yarrow
#

yep makes sense

#

how does it all tie in to factorial?

#

badly phrased, I know "how" they are related, but not how to implement factorial finally

stark fable
#

well there are a few other things we need for factorial

#

firstly, we need pairs

#

pair is lambda a:lambda b:lambda c:c(a)(b)

#

first is lambda a:lambda b:a and second is lambda a:lambda a:a

#

then once we've got that, factorial ends up as lambda n:n(lambda p: pair(mult(p(first))(p(second)))(add_one(p(second))))(pair(one)(one))(first)

#

@rare yarrow

rare yarrow
#

@stark fable thanks!

#

btw I've seen first and second called true and false before

formal sandal
#

Yes, that's the same thing

#

Because they can encode booleans.

#
(condition)(then-value)(else-value)
rare yarrow
#

yep

#

thanks!

formal sandal
#

I have no idea why I did that, you can also do fst = (rename fst true)

glacial rampart
#
🐍 class Foo:
••      @classmethod
••      @property
••      def foo(cls):
••              return 1
•• 
🐍 Foo.foo
<bound method ? of <class '__main__.Foo'>>

pretty sure i just broke the descriptor protocol lol

brisk zenith
#

!remind 10h look for your fluent python book and learn about damn descriptors for fucks sake <3

night quarryBOT
#
Sure thing!

Your reminder will arrive in 10 hours!

formal sandal
#

Better not specify minutes...

brisk zenith
#

haha, yeah i'd like to receive the reminder this year :D

night quarryBOT
marsh void
#

can relate

minor palm
#

!e from future import braces

night quarryBOT
#

@minor palm :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: not a chance
thin trout
#

!e from future import braces

night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

https://github.com/NeKitDS/braces.py
bitter iris
#

perfection

formal sandal
#

Would it be unreasonable to propose a collaborative project for #esoteric-python?

thin trout
#

I don't think it would be, there was esoteric challenges after all before

#

It would be a good fit for a user event too

brisk zenith
#

ooh i've had that sort of idea before, i think it would be super fun to arrange.

snow beacon
#

Would it be better to do something with lots of different pieces that people can put their own spin on, or one bit of code that everyone overcomplicates?

marsh void
#

Why is everyone talking about my version of braces haha

#

it completely fucks up the lines as of now

#

I mean their numbers

gilded orchid
#

maybe every month there could be a new esoteric project that everyone could work on on github

#

suggestion: a library to help with creating #encoding: xyz things

formal sandal
#

I've been thinking about creating an esolang. It would look like a completely normal language at the first glance, but it has so many inconsistencies and weird features that it's practically impossible to create a more or less meaningful program with it.

#

Maybe someone would find that project interesting, because it's so massive that I probably won't manage it on my own

#

I wrote the gist to give you an idea of the weirdness level.

void geode
#

Hello i need help. I am new to coding python and i have a starting project as coding a bot that could paste a text and tag a person and post the text too. The bot works great when just typing the text and posting it. What the bot is failing to do is to tag a person. Please could someone help me with this thanks!.

stark fable
#

wrong channel

#

this is the channel where people mess around with python and do things like this py factorial = lambda b:(lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(b)(lambda b: lambda a:a(b(lambda a:lambda a:a)(b(lambda a:lambda b:a)(lambda a:lambda b:lambda c:a(b)(b(c))))(lambda a:lambda a:a))(lambda a:lambda c:b(lambda a:lambda a:a)(a)(a(c))))(lambda a:a(lambda a:a)(lambda a:a))(lambda a:lambda b:a)(lambda a:a+1)(0)

bitter iris
#

suggestion: a library to help with creating #encoding: xyz things
@gilded orchid we already have one 😎 BRM

sick hound
snow beacon
#

It puts some much-needed fun into Stack Overflow.

earnest wing
#

!e print(exit.dict)

night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

{'name': 'exit', 'eof': 'Ctrl-D (i.e. EOF)'}
thin trout
#

Hmmhm?

#

What is exit.eof?

hardy falcon
#

!e print(exit.dict['eof'])

night quarryBOT
#

@hardy falcon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'Quitter' object has no attribute 'dict'
hardy falcon
#

🙃

thin trout
#

I mean

#

!e print(exit.eof)

night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

Ctrl-D (i.e. EOF)
edgy kelp
#
    if os.sep == ":":
        eof = "Cmd-Q"
    elif os.sep == "\\":
        eof = "Ctrl-Z plus Return"
    else:
        eof = "Ctrl-D (i.e. EOF)"

    class Quitter(object):
        def __init__(self, name):
            self.name = name

        def __repr__(self):
            return "Use {}() or {} to exit".format(self.name, eof)

        def __call__(self, code=None):
            # Shells like IDLE catch the SystemExit, but listen when their
            # stdin wrapper is closed.
            try:
                sys.stdin.close()
            except:
                pass
            raise SystemExit(code)

    builtins.quit = Quitter("quit")
    builtins.exit = Quitter("exit")
sick hound
#

... they use the separator for identifying the OS?

#

clever, i guess

thin trout
#

Which OS uses : blobthinkingdown

sick hound
#

according wikipedia, Classic Mac OS and Apple's GS/OS

brisk zenith
#

i can't seem to see any part of cpython which uses os.sep = ":" anymore

edgy kelp
#

looks like it's a bit different in my venvs (some outdated version?)
normal installs use

    if os.sep == '\\':
        eof = 'Ctrl-Z plus Return'
    else:
        eof = 'Ctrl-D (i.e. EOF)'

and the QUitter looks the same but is defined in a separate module and eof is passed as an instance var

frozen holly
#

remimds me of

if 3/2 == 1:
  input = raw_input
runic rivet
#

@frozen holly What a beautiful peace of code 😂

frozen holly
#

which is also a beautiful peice of code

wary shoal
#

Beautiful piece of code right there.

#

my pc would sure burn if i ran that.

rare yarrow
#

@frozen holly funnily enough, there was another "my_first_calculator" program I saw recently which also had to do with input on python2

#

it was from a CTF contest

#

relevant code:

#
#!/usr/bin/env python2.7

try:
    print("Welcome to my calculator!")
    print("You can add, subtract, multiply and divide some numbers")

    print("")

    first = int(input("First number: "))
    second = int(input("Second number: "))

    operation = str(raw_input("Operation (+ - * /): "))
    
    # red herring terrible code to calculate the answer

except ValueError:
    pass
#

note that it is python2.7

#

there's a flag.txt on the server but it's pretty easy to even get a root shell

#

My solution was to enter ||__import__('subprocess').call(['cat','flag.txt'])|| for the first prompt

#

I'm actually curious if there are any other solutions

midnight bane
#

!e ```python
import inspect
print(inspect.getsource(exit.class))

night quarryBOT
#

@midnight bane :white_check_mark: Your eval job has completed with return code 0.

001 | class Quitter(object):
002 |     def __init__(self, name, eof):
003 |         self.name = name
004 |         self.eof = eof
005 |     def __repr__(self):
006 |         return 'Use %s() or %s to exit' % (self.name, self.eof)
007 |     def __call__(self, code=None):
008 |         # Shells like IDLE catch the SystemExit, but listen when their
009 |         # stdin wrapper is closed.
010 |         try:
011 |             sys.stdin.close()
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/usililojoh

midnight bane
#

Where was the quitter that used os.sep from

tribal moon
#
(lambda response: (lambda word, definition: print(f'Random Word: {"".join(word)}', f'Definiton of {"".join(word)}: {"".join(definition)}', sep='\n'))([item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('div', {'id': 'random_word'})], [item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('div', {'id': 'random_word_definition'})]))(__import__('requests').get('https://randomword.com/'))``` random word
#
(lambda response: print(f"Top 10 synonyms for your word are {', '.join([item.text for item in __import__('bs4').BeautifulSoup(response.content, 'lxml').find_all('a', {'data-linkid': 'nn1ov4'})][0:9])}"))(__import__('requests').get(f'https://www.thesaurus.com/browse/{input("Find synonym for: ")}'))```
#

10 synonyms of a word

marsh void
#

since we had some nice ctypes.Structure wrapper with annotations, I thought, why not do the same with functions? ```py
import ctypes
import functools
from typing import Any, Callable

FuncPtr = ctypes._CFuncPtr

def func_def(func_ptr: FuncPtr) -> FuncPtr:
def wrap(func: Callable) -> Callable:
try:
annotations = func.annotations

    except AttributeError:
        pass

    else:
        return_type = annotations.pop("return", None)

        if return_type:
            func_ptr.restype = return_type

        arg_types = list(annotations.values())

        if arg_types:
            func_ptr.argtypes = arg_types

    @functools.wraps(func)
    def handle_call(*args) -> Any:  # do not support keywords yet
        return func_ptr(*args)

    return handle_call

return wrap```
#
kernel32 = ctypes.WinDLL("kernel32.dll")


@func_def(kernel32.ReadProcessMemory)
def read_process_memory(
    handle: wintypes.HANDLE,
    base_address: wintypes.LPVOID,
    buffer: wintypes.LPCVOID,
    size: ctypes.c_size_t,
    size_ptr: ctypes.POINTER(ctypes.c_size_t),
) -> wintypes.BOOL:
    pass``` usage is pretty straightforward
signal matrix
#

what ways are there to compile a python package into a single file . The use case is a jupyter notebook attached to a tiddlywikky file

snow beacon
#

Is this really the channel for that?

formal sandal
#

Well, if you create an entire operating system in Python, then you can simply create all the necessary files inside of it and then run the interpreter.

snow beacon
#

You could probably fit all of the code at the end of a PNG file.

#

I couldn't get the one in the github repo to work, but it's probably possible.

earnest wing
#

Just be careful to account for the huffman encoding.

rugged sparrow
#

@signal matrix python allows for running zip files that have a __main__.py file in them

#

i say running because it really just decompresses on the fly

#

@gritty gull wrong channel

#

@snow beacon you can create a python runnable png file by doing cat png_file.png python_package.zip > target.png

#

then just python target.png

signal matrix
#

@rugged sparrow I was thinking about a way to prevent this folder from being 30,000 files and you just solved my issue with packaging some stuff simply by mentioning ZIPFILE omfg I am stupid

#

Im making a portable anaconda/tiddlywiki/jupyter/stuff folder setup and its at 10 gigs and about 32,000 files... you can just read the zip contents and pull a single file out with a script without having to decomppress the entire archive right?

rugged sparrow
#

i think theres some sort of partialunzip

signal matrix
#

nice, thanks. I hope what I am tryingto make works, that would be neato to have an anaconda/cmdr/nuikta/jupyter portable development environment I can use for learning and keeping all my stuff in the same place

#

I want to make it entirely in a chrome browser with selenium and jupyterlabs and tiddlywiki with cmdr for finicky stuff

tribal moon
brisk zenith
#

yes.

#

__import__('builtins',level=False).__dict__['type'] is just a really round-about way of saying type

#

!e ```py
x = import('builtins',level=False).dict['type']
y = type
print(x == y, x is y)

night quarryBOT
#

@brisk zenith :white_check_mark: Your eval job has completed with return code 0.

True True
tribal moon
#

Well I tried to make it looks as bad as possible

signal matrix
#

is there a way to get an actually portable, non-install version, of anaconda on windows? I want to just have a folder I can image and carve for modifications and portability.

distant wave
#

I just wrote this to get around an irritating url format issue as a workaround:

#
self.raw_url[self.raw_url.index("/dur/"):self.raw_url.index("/dur/")+18][len("/dur/"):].partition("/")[0]
distant wave
#

Cleaned up:

#
data = collections.defaultdict(list)
for match in re.finditer(r"/([^/]+)/([^/]+)", working_url):
    data[match.group(1)] += match.group(2).split(",")
#

!e ```py
import re
from collections import defaultdict
from urllib.parse import parse_qs, urlparse

url_1 = "https://example.com/sharing?name=bob&source=utm_campagin&dur=15&share_link=1233"
url_2 = "https://example.com/sharing/name/bob/source/utm_campaign/dur/15/share_link/1233"
print(parse_qs(urlparse(url_1).query))
data = defaultdict(list)
for match in re.finditer(r"/([^/]+)/([^/]+)", url_2[len("https://example.com/sharing"):]):
data[match.group(1)] += match.group(2).split(",")
print(dict(**data))

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

001 | {'name': ['bob'], 'source': ['utm_campagin'], 'dur': ['15'], 'share_link': ['1233']}
002 | {'name': ['bob'], 'source': ['utm_campaign'], 'dur': ['15'], 'share_link': ['1233']}
snow beacon
#

At least they fixed the spelling.

formal sandal
#

One very annoying thing about recursion is that when you change the name of a function, you have to change it everywhere in its body. But not all is lost!

#

!e

from functools import wraps

_Y_STACK = []


def y():
    return _Y_STACK[-1]


def rec(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        _Y_STACK.append(f)
        try:
            return f(*args, **kwargs)
        finally:
            _Y_STACK.pop()
    return decorated


@rec
def factorial(n):
    if n <= 0:
        return 1
    else:
        return n * y()(n - 1)


print(factorial(42))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

1405006117752879898543142606244511569936384000000000
formal sandal
#

I believe you can do something similar to emulate this from JavaScript, but I'm not that evil.

#

(I screwed up -- it should be _Y_STACK.append(decorated) instead of _Y_STACK.append(f))

formal sandal
#

hey

rugged sparrow
#

!e ```py
import dis

def rec(f):
f.code = f.code.replace(
co_consts=f.code.co_consts + (f,)
)
idx = f.code.co_consts.index(f)
bcode = bytearray(f.code.co_code)
for i,c in enumerate(bcode.copy()):
if c in [dis.opmap['LOAD_GLOBAL'], dis.opmap['LOAD_NAME']] and f.code.co_names[bcode[i+1]]=='this':
bcode[i] = dis.opmap['LOAD_CONST']
bcode[i+1] = idx
f.code = f.code.replace(
co_code = bytes(bcode)
)
return f

@rec
def factorial(n):
if n <= 0:
return 1
else:
return n * this(n-1)

print(factorial(42))```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

1405006117752879898543142606244511569936384000000000
rugged sparrow
#

@formal sandal i am that evil ^

formal sandal
#

You are that evil...

#

Can you make this work so that when you run it in the top-level, this is None, but when you run it in an object belonging to a special @thisable/Thisable class, this will be the instance of the object we're currently in?

rugged sparrow
#

making this a function would make that relatively trivial withinspect

#

otherwise it would need to be a wrapped func/class

#

would just need to make the wrapping loop for classes

snow beacon
#

@formal sandal Would it not do that with a simple this = None at the top level?

formal sandal
#

Well, you'll still have to implement getting the context inside an arbitrary function

#

I'm gonna try to make it in Haskell

#

That would be some weird twist on State

tribal moon
#

does this belong here

#
(lambda main: main(__import__('builtins').__dict__['dict'](add=lambda x, y: x + y, subtract=lambda x, y: x - y, multiply=lambda x, y: x * y, divide=lambda x, y: x/y)))(lambda run:__import__('builtins').__dict__['print'](run[input('>>> add, subtract, multiply, or divide ').lower()](__import__('builtins').__dict__['int'](input('Num 1: ')), __import__('builtins').__dict__['int'](input('Num 2: ')))))```
#

I tried making is as bad as possible

midnight bane
proper frigate
vague hearth
#

idk why as such but they both just take twice as much as their integer counter part ```python

from sys import getsizeof
getsizeof(0)
12
getsizeof(1)
14

proper frigate
#

Luck boy

>>> from sys import getsizeof
>>> getsizeof(0)
24
>>> getsizeof(1)
28
#

what are you running on ? I want 12-bytes booleans too !

formal sandal
#

oh

#

maybe I got it? 🤔

#

maybe it has something to do with the implementation of bigints.

proper frigate
#

dunno…
let's grep cpython's source code for True and False to find out ! 😄

vague hearth
#

wait, why are my ints different sizes? mine was on 3.6 i think, maybe they changed it in more recent versions?

formal sandal
#

It seems that zero has zero "blocks"?..

#

Each "digit" is 32 bits (of space) long, and zero just has 0 digits

proper frigate
#

put this way, it seems logical
and as bool is a subtype of int, it makes sense.

#

Thanks for the answer, anyway !

stark fable
#

@vague hearth you used 32-bit python

vague hearth
#

so I did, didn't notice thx, was confused

formal sandal
#

Dear Reader, I'm sorry in advance, but this will be a long one!

#

!e

import gzip;import base64;exec(gzip.decompress(base64.b85decode(b'ABzY8&LZPp0{^8|+m6~W5Pi>AjCdiTl)j@b+Fn-Gsx7L-zEn{ZIf=tsjcsI`7IwwIcbtopKo<7G3&}Wh=FFU#ajqnXd@E8TWubxbjZ_8-wT)Af-c!$u?|%Qf`SRn_Y88LJU4Fe?ep|s6JRUqRqd8=f>NsH{V`3fC9n(hpCY^!_<{scrQL|M7ObSfE5EKy^m?sWHlSZDG7DQ`^R~wqLoTYbre6Xe}fF%*fOfVD2zNSTvu`xcc<J+IL&XB<sp7f0zZQLtu*DhtBlbvP{^lB*u4LU*A)DUBoi&MS`!f7X#QTz6#Q-GoDYF<(Gz@yLsMh=4RQo1qlo$haxlB$oLBmJ6`UxUp|m)8)Jg773GFd=HKr!blP`DdTzkk?rq9Ryyd0*Y>$^gB7%!1?IosYvix6FY>}6F)?YQ6uUzv^>$#%J>q=n4#Rkb=!jFz%&!u5RoFnw8jqx_2aD~g{H$2pCs>szNCgHrJKd2m~nitg|i?yqy^<vm~zz80_FOEicP_OSJj{`Xhu`1h>^-Kr<_UAuK~J)kmp9QpY0PLg@_YXi{Uw6hL$Qw1q~^er3Gn>C*|qdYn#ijs*Q2Q$1ruK<?P?}4!ko2+brDn^1N#YT=(uzDM(h~Ut<p$mU3$DW!970x}(_GT)R1p$vA-b3m9`C<Bs%%X$nheZW~!?Rt~#&7Thk~3YwF7g*k;>*f2H-hr~roI?+a>k-u161^E9~2K<34X(<e4#fI+&teRvQa-Q+wL90Fp@jSwo;FNF79%BUO=I?d%*IT0M3MO+%@cL`=@PmFL$?!^;breP)2rlmk>(i7iI8RUC%fIwQV4ln?MW5F8xzY}{G}iunPdi1r`n|S+$Yw*EF17>0F~fcNU#Iu>G2y8cDKT{+@tzxpJQ{+hdRy4b1-HX+<K?)mxLuQ6A8Xrpby-yh<pprm2i1wypxx!oXcRaofp=8xVBWZf(Pb~kfM9R8t_0pea_mixoLx)rIx%<ACAVfB5xaz1Prc=6+xWS#Z5&LIesBrObw08E-eU0tCQwj;2f=^+gW@!|3IG5')))

def pythagorean_triples(n: int) -> [(int, int, int)]:
    base = list(range(1, n))
    return Monad[list].__bind__(
        base,
        lambda a: Monad[list].__bind__(
            base,
            lambda b: Monad[list].__bind__(
                base,
                lambda c:
                    Monad[list].__shove__(
                        Monad[list].__guard__(
                            a < b
                        ),
                        Monad[list].__shove__(
                            Monad[list].__guard__(
                                a**2 + b**2 == c**2
                            ),
                            Monad[list].__return__(
                                (a, b, c)
                            )
                        )
                    )
            )
        )
    )

print(pythagorean_triples(24))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
formal sandal
#

pythagorean_triples n is all integer-sided right triangles with all sides less than or equal to n

#

Actually, it should've been range(1, n+1), but that's a self-nitpick

#

In Haskell, that would be written as:


pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n = 
    let
        base = [1..n]
    in
        base >>= (\a ->
            base >>= (\b -> 
                base >>= (\c ->
                    guard (a < b) >>
                    guard (a^2 + b^2 == c^2) >>
                    return (a, b, c)
                )
            )
        )

Which is such a common pattern that there's a special notation for that:

pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n = do
    let base = [1..n]
    a <- base
    b <- base
    c <- base
    guard (a < b)
    guard (a^2 + b^2 == c^2)
    return (a, b, c)
#

In turn, it's the same as a list comprehension

pythagoreanTriples :: Integer -> [(Integer, Integer, Integer)]
pythagoreanTriples n =
    let
        base = [1..n]
    in
        [(a, b, c) | a <- base, b <- base, c <- base, a < b, a^2 + b^2 = c^2]
#

The best part of that compressed library is that I can do this:

@implement(Monoid, list)
def __mempty__(): return []

@implement(Monoid, list)
def __mappend__(a, b): return a + b

@implement(Monad, list)
def __return__(x): return [x]

@implement(Monad, list)
def __bind__(ma, fn): return sum(map(fn, ma), [])

@implement(Monad, list)
def __shove__(ma, mb): return mb * len(ma)
earnest wing
#

I know it's not related, but I can't help but to think of Rust-like #[derive] macros when I see that.

plain moon
#

Rust's traits and Haskell's typeclasses are closely related actually, both support derivation

formal sandal
#

refactoring

def pythagorean_triples(n: int) -> [(int, int, int)]:
    with do(list):
        base = list(range(1, n))
        return\
                                                        Monad.__bind__(
            base,
            lambda a:                                   Monad.__bind__(

            base,
            lambda b:                                   Monad.__bind__(

            base,
            lambda c:                                   Monad.__shove__(

            Monad.__guard__(a < b),
                                                        Monad.__shove__(
            Monad.__guard__(a**2 + b**2 == c**2),

            Monad.__return__( (a, b, c) )

            )))))

(haven't published the wither yet)

#

screw you, PEP 8

#

You have no bearing on haskell

stuck rune
#

Hey guys, I'm messing around with using utf8 characters in identifiers. Some "special characters" seem to work, but do my disappointment, emojis don't (although they are also in utf8 ?). Does somebody know what the exact limitations are?

edgy kelp
#

!d identifiers

night quarryBOT
#
2.3. Identifiers and keywords Identifiers (also referred to as names) are described by the following lexical definitions. The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details. Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first [...]```
None
edgy kelp
#

That's a horrible embed but the link has the explanation

stuck rune
#

thanks

tranquil pendant
#

Anyone familiar with kite/atom?

#

wondering how on earth to set the kite copilot to top window. doesn't seem to be any option to. surely this isn't restricted to paid version right

formal sandal
#

@tranquil pendant This is not the right channel, please read the channel description

tribal moon
#
(lambda: print('Welcome to the matrix') if (lambda root, tk, random: root.configure(background='black') or root.attributes('-fullscreen', True) or [tk.Label(root, text=random.choice([0, 1]), bg='black', fg='green', font=('fixedsys', 18)).grid(row=_, column=random.randint(0, 100)) or root.after(1, None) for _ in range(1, 30) for __ in range(50)])(__import__('tkinter').Tk(),__import__('tkinter'), __import__('random'))[0] is None else False)()
``` Matrix
solar dove
#

^ I'm officially cross-eyed now

earnest wing
#

Here's an idea I've been toying with:

earnest wing
#
from types import FunctionType
from typing import Any
import inspect

class fn:
    def __init__(self, *args, return_state=False):
        self.args = args
        self.return_state = return_state

    def __rshift__(self, other):
        if self.return_state:
            return NotImplemented
        self.ret = other
        self.return_state = True
        return self

    def __repr__(self):
        get_name = lambda x: x.__qualname__ if isinstance(x, type) else repr(x)
        if hasattr(self, "ret"):
            return f"fn({', '.join(map(get_name, self.args))}) >> {get_name(self.ret)}"
        return f"fn({', '.join(map(get_name, self.args))})"

    def __eq__(self, other):
        if isinstance(other, fn):
            if hasattr(other, "ret") and hasattr(self, "ret"):
                return self.args == other.args and self.ret == other.ret
            elif hasattr(other, "ret") ^ hasattr(self, "ret"):
                return False
            return self.args == other.args
        return NotImplemented

def _type(obj):
    if isinstance(obj, FunctionType):
        sig = inspect.signature(obj)
        args = [
            Any if arg.annotation == inspect.Parameter.empty else arg.annotation
            for arg in sig.parameters.values()
        ]
        if sig.return_annotation == inspect.Signature.empty:
            return fn(*args, return_state=True)
        return fn(*args) >> sig.return_annotation
    return type(obj)

And this gives you...

def foo(a: int, b: int) -> int: return a + b
def bar(x, y): pass

assert _type(foo) == fn(int, int) >> int
assert _type(bar) == fn(Any, Any)
thin trout
#

That's pretty cool

#

Maybe you should rename _type to signature

earnest wing
#

I want to eventually expand this into a proper type system with generic types & pattern matching

proper vault
#

Are you going to have dependent types?

sick hound
neat otter
#

pretty amazing

lament ibex
#

Now we need a script that given a poem auto generates all the modules to make valid Python code

sick hound
#

That's a good project @lament ibex . A poem template generator. Love it

#

pretty amazing
@neat otter ha ... Programming techniques not recommended for production ...

formal sandal
#

because of the indentation business

sick hound
#

Good call @formal sandal - indentation is crucial to meaning in poetry, as it is in python of course.

I'm not sure which other languages can use this technique of hacking the global namespace. Probably only dynamic rather than compiled lanuages

obtuse obsidian
#
#GPL3 https://www.gnu.org/licenses/gpl-3.0.en.html
#LyfeOnEdge
###Troll script for discord.
###Puts every letter in your copy/paste clipboard in a spoiler
###Clever cyclic program means that it doesn't care if it has alrady been converted
###Original input -> Converted output -> Identical converted output
###Requires pyperclip (pip install pypercip)

##How to use:
##Set mode below
##Start script with `python clippyspoiler.py`
##Copy with ctrl+c or right-click -> copy
##Text strings will be turned into spoilers automatically
##Paste with ctrl+v or right-click -> paste
##To stop the automatically spoiler exit the script

import sched, time
import pyperclip
words = True  #Don't touch this
chars = False #Don't touch this

#set mode to either words or chars
#chars will spoiler every character
#words will spoiler every word

mode = chars #Change this to 'words' or chars'

s = sched.scheduler(time.time, time.sleep)

def loop(sc): 
    data = pyperclip.paste()
    data = data.strip().replace("|","")

    newdata = ""
    for w in data:
        if mode == words:
            newdata += "||{}||".format(w)
        else:
            for c in w:
                newdata += "||{}||".format(c)

    pyperclip.copy(newdata)
    s.enter(1, 1, loop, (sc,))

s.enter(1, 1, loop, (s,))
s.run()
#

once you realize how the loop can take an input, make an output, then take that output as the input and get the same output cyclically after it's quite satisfy

#

like Input0 -> Output0 which becomes Input1 -> Output1 and Input0 != Ouput0, Input1 = Output1

earnest wing
#
" ".join(map(lambda x: f"||{x.replace('|', '')}||", data.split())) if word else map(lambda x: f"||{x}||", filter(lambda x: x != "|", data))
#

Or with listcomp:

#
"".join([f"||{x.replace('|', '')}||" for x in data.split()] if word else [f"||{x}||" for x in data if x != "|"])
obtuse obsidian
#

🤷‍♂️ I'm not great at one liners

sick hound
#

hi

marsh void
#

type("",(),{}) ah yes my favorite <class ''>

formal sandal
#

Golf it!
I don't know which one is better

"".join([f"||{x.replace('|', '')}||"for x in data.split()]if word else[f"||{x}||"for x in data if"|"!=x])
"".join([f"||{x.replace('|', '')}||"for x in data.split()]if word else[f"||{x}||"*("|"!=x)for x in data])
stark fable
#

well firstly there's a redundant space py "".join([f"||{x.replace('|','')}||"for x in data.split()]if word else[f"||{x}||"for x in data if"|"!=x]) "".join([f"||{x.replace('|','')}||"for x in data.split()]if word else[f"||{x}||"*("|"!=x)for x in data])

#

you can also change if/else to and/or py "".join(word and[f"||{x.replace('|','')}||"for x in data.split()]or[f"||{x}||"for x in data if"|"!=x]) "".join(word and[f"||{x.replace('|','')}||"for x in data.split()]or[f"||{x}||"*("|"!=x)for x in data])

#

(i think that works)

gaunt rivet
#

Also it is going forever, it does not just print that.

formal sandal
#

I could do it in just one

#

but that's a very long one

sick hound
#

My attempt, nothing too impressive, but it's fairly short: ```py
import math;i=0;n=60
while 1:i+=1;print('#'*(int(math.sin(i/n)*n+n)))

#

68 characters

formal sandal
#

It's very beautiful with a delay:

import math;i=0;n=60
while 1:i+=1;print('#'*(int(math.sin(i/n)*n+n)),*(0*[x**x for x in range(1000)])); 
sick hound
#

My CPU isn't a fan of that delay

#

But it does look nice 😄

formal sandal
#

After that delay, my computer in general is a fan

#

a very loud one

dapper parrot
#

i'm wondering if you can do a crude sin approximation to avoid the import

sick hound
#

I'm guessing that would probably be longer than the import

tribal moon
#

Artificial BSoD for Windows 10 screen designed to look like Pacman in 1 line

#
((lambda: ([['pacman.png', None, None, True, False], ['blueghost.png', None, None, False, True], ['pinkghost.png', None, None, False, True], ['redghost.png', None, True, True, True]])), ((lambda : __import__('builtins').__dict__['open']('stats.gif', 'wb+').write(__import__('requests').get(__import__('base64').b64decode(__import__('requests').get('https://hastebin.com/raw/imequhafih').content)).content))(), (lambda image: image.resize((__import__('ctypes').windll.user32.GetSystemMetrics(0), __import__('ctypes').windll.user32.GetSystemMetrics(1))).save('stats.gif'))(__import__('PIL.Image').Image.open('stats.gif')), (lambda LABEL, root, tk: [(tk.Label(root, image=photo).pack() or root.attributes('-fullscreen', True), None)[1] for LABEL['photo'] in [(tk.PhotoImage(file=(__import__('os').getcwd()+'\\stats.gif')))]][0])(globals(), __import__('tkinter').Tk(), __import__('tkinter')) if __import__('sys').getwindowsversion().major == 10 else False), (lambda PACMAN: True if PACMAN else False or PACMAN is not None), (lambda REDGHOST, PINKGHOST, BLUEGHOST: [True if GHOST_SPRITE is not None else False for GHOST_SPRITE in [REDGHOST, PINKGHOST, BLUEGHOST]]), lambda install_sprites:```
#
 [True or install_sprites(sprite_link) for sprite_link in ['https://static.giantbomb.com/uploads/square_small/8/87790/2469740-blinky.png', 'https://static.giantbomb.com/uploads/square_small/8/87790/2469744-pinky.png', 'https://p.kindpng.com/picc/s/149-1494722_text-pacman-ghosts-ms-area-free-transparent-image.png']], (lambda DISPLAY_MAP, ALL_SPRITES_GENERATED: DISPLAY_MAP if ALL_SPRITES_GENERATED in ['red', 'pink', 'blue'] else False), (lambda PELLETS, POWERPELLETS, KILL_MODE: KILL_MODE if POWERPELLETS else PELLETS+1), (lambda UP, RIGHT, LEFT, DOWN: UP or True if UP else DOWN or RIGHT if True else LEFT), (lambda LIVES, PACMAN_IS_HIT: LIVES - 1 if PACMAN_IS_HIT else True), (lambda TKHANDLER, TKREPORT, ROOT, tkinter_, tkinter_magic_lib, PHOTOIMAGE: [[],[],[],...,[...,...,...],['i','j',[TKHANDLER, TKREPORT, ROOT, [tkinter_, tkinter_magic_lib], PHOTOIMAGE]]]), (lambda FINAL_RUN, PACMAN_IS_DEAD, POINTS, _display: _display('YOU WIN!') if POINTS > 10000 else False if PACMAN_IS_DEAD and FINAL_RUN else True))```
sick hound
#

This looks horrible, good job my friend

formal sandal
#

Artificial BSoD?

tribal moon
#

it makes a GUI that looks like a BSoD

formal sandal
#

oh

tribal moon
#

it really isn't

#

and you can just press Alt F4 to exit it

sick hound
#

Damn, it works

formal sandal
#

Could you show how it looks?

sick hound
#

Like a blue screen

#

but it only appears on one screen

dapper parrot
#

doesn't seem to do anything for me

tribal moon
#

Are you on windows 10?

dapper parrot
#

yep

tribal moon
#

hm

dapper parrot
#

no new windows or anythnig

tribal moon
#

strange

#

does it output anything?

dapper parrot
#

nope

tribal moon
#

hmmm

#

Well I can't fix it anymore

#

because I wrote this like 2 hours ago

#

and I can't even understand it

#

can you show me the output of print(sys.getwindowsversion().major)

#

because if it isn't 10, then I think it won't work

formal sandal
#

well

#

!e

def sin(x): 
     x %= 6.28 
     if x>3.14: 
         return -sin(x-3.14) 
     return x-x**3/6+x**5/120-x**7/5040+x**9/362880 
i=0;n=60 
while 1:i+=1;print('#'*(int(sin(i/n)*n+n)),*(0*[x**x for x in range(1000)])); 
#

: - (

#

I don't think it can be shortened

tribal moon
#

shorten what

sick hound
#

Printing a never ending sinus wave

formal sandal
#

I mean, if math is not allowed

#

Well, you could put everything on one line

#

And even inline the function

tribal moon
#

math isn't allowed?

#

why

sick hound
#

No, math is allowed, it's typing's would be shortest if math wasn't allowed

#

The module math

tribal moon
#

oh

#

that can be onelined

gaunt rivet
#

A sine wave

#

Also i am using delay.

zealous widget
#
In [35]: while True: 
    ...:     print(int(20 * np.sin(time.time()) + 20) * ' ' + '###') 
    ...:     time.sleep(.1) 
#
In [38]: while True: 
    ...:     print(f'{"###":>{int(20 * np.sin(time.time()) + 20)}}') 
    ...:     time.sleep(.1) 
#

looks the same

#

i think you can one-line this with a tuple

#
In [39]: while True: (print(f'{"###":>{int(20 * np.sin(time.time()) + 20)}}'), time.sleep(.1)) 
    ...:  
    ...:                                                                                                                                                      
              ###
            ###
          ###
         ###
       ###
     ###
   ###
  ###
 ###
###
###
###
###
###
#

and use while 1 to shorten it

#

and remove spaces:

In [41]: while 1:(print(f'{"###":>{int(20*np.sin(time.time())+20)}}'),time.sleep(.1))    
gaunt rivet
#

Yeah but that is not a real sine wave, mine is created from actuall math.sin() data

tawny arch
#

math.sin and np.sin will act the same here

formal sandal
#
i,n=0,60
while 1:i+=1;print(" "*(int(__import__("math").sin(i/n)*n+n))+"###");[x**x for x in range(1000)]
#

Don't see why that's not a real sinewave.

hollow patrol
#

I'm going to make a python program to scoper

#

which uses dictionaries for variables over setting them

#

and then feed that scoper into my one-linerizer

sick hound
#

I'm going to make a python program to scoper
which uses dictionaries for variables over setting them
and then feed that scoper into my one-linerizer
oh no...

sick hound
#

Python that's written not to be good, but horrible. Code that's really short or really unreadable or special in any way. Basically Python written for purposes other than having practial and well readable source code.

snow beacon
#

For instance: [0x_for id in range(10)], which doesn't do what you expect.

sick hound
#

That said, can anyone beat this console mandelbrot printer when it comes to character count: ```py
x=0;y=0;i=50;b=complex;z=i;q=print
while y<i:
o=b(y/i-0.8,x/i-0.5)2.2;c=b(0,0);p=0;x=x+1%i;x%=i+1
if x==1:q();y+=1
while p<z and abs(c:=c
c+o)<2:p+=1
q("#"if p==z else' ',end=' ')

This is 191 chars.
snow beacon
#

How about:

sick hound
snow beacon
#
x=0;y=0;i=50;b=complex;z=i;q=print
while y<i:
 o=b(y/i-0.8,x/i-0.5)*2.2;c=b(0,0);p=0;x=x+1%i;x%=i+1
 if x==1:q();y+=1
 while p<z and abs(c:=c*c+o)<2:p+=1
 q("#"if p==z else' ',end=' ')```
sick hound
#

Hmm, yes that's better, didn't even think of that 😄

snow beacon
#

You can do x=y=0 on the first line.

edgy kelp
#

Can use newlines instead of semicolons for the same char count fwiw... And the ternary can be replaced by an indexed string

snow beacon
#

i=z=50

sick hound
#

Ahh that's cool. Didn't even know you could do that

proper vault
#

b(0,0) this can just be 0, so you can remove the b variable and just use complex directly in the other case

snow beacon
#

Can't it even be b()?

proper vault
#

yeah, though that is longer

sick hound
#

b() works

proper vault
#

the python3 number model means you can use an int in place of a complex number and still get correct results.

sick hound
#

and c=0 does too

#

interesting @proper vault

proper vault
#

x=x+1%i this is just x+=1 no?

sick hound
#

It's x+= 1 but when x is 50, it's reset to 0

snow beacon
#

You mod by i+1 just after?

proper vault
#

but % has higher precedence than +

#

so it is x + (1 % i)

#

x==1 unless x can be negative, you can make it x<2

sick hound
#

Ah, makes sense

proper vault
#

oh wait, x can be zero

#

nvm

snow beacon
#

Maybe there's something to be done with ~ to save a space.

#

Never mind, you'd need a minus.

sick hound
#

Okay, so this is the current code ```py
x=y=0;i=50;b=complex;z=i;q=print
while y<i:
o=b(y/i-0.8,x/i-0.5)2.2;c=p=0;x+=1;x%=i
if x==1:q();y+=1
while p<z and abs(c:=c
c+o)<2:p+=1
q("#"if p==z else' ',end=' ')

165 chars, instead of 191^^
snow beacon
#

"#"if p==z else' ' -> " #"[p==z]

sick hound
#

Oh, that's a good one

proper vault
#

x+=1;x%=i
x=-~x%i this seems like there is even more to do though

#

0.8 can be .8, same with .5

snow beacon
#

I'm looking at the if at the moment.