#esoteric-python

1 messages ยท Page 89 of 1

proper vault
#

complex(y/i-0.8,x/i-0.5) will be shorter once you remove the b=complex;

sick hound
#

Ah yeah, since it's only needed in one place now

proper vault
#

aren't z and i always the same thing?

sick hound
#

Hmm, they could be the same thing

snow beacon
#

Neither changes.

#

Both are 50.

sick hound
#

Yeah, they are unrelated but can be the same with no problem^^

#

z used to be the iteration depth

#
x=y=0;i=50;q=print
while y<i:
 c=p=0;x=-~x%i
 if x==1:q();y+=1
 while p<i and abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)<2:p+=1
 q(" #"[p==i],end=' ')

141 chars now

snow beacon
#

You don't need to assign to o. It's only used once.

#

Oh, maybe you do.

#

For sequencing, that is.

proper vault
#

seems to work fine

sick hound
#

True, o is never changed therefore the assignment is unnecessary

proper vault
#

if will sometimes get different y value though

snow beacon
#

Could you do something like while abs(c:=c*c+o)<2:p+=p<i? Or might that loop forever?

#

Can o be 0?

#

And you still don't need indents that big.

#

One space is sufficient.

sick hound
#

Yeah, my editor forces me to write them

snow beacon
#

If o can be zero, you could do while(abs(c:=c*c+o)<2)*o:p+=p<i so it doesn't get stuck in a loop.

#

Wait, no, that's different logic.

#

Oh, right, o is gone.

stark fable
#

is it possible for p to end up being bigger than i?

sick hound
#

Yes

snow beacon
#

Not with the current loop condition?

sick hound
#

Well, no

#

There needs to be some mechanism in place, so that the loop doesn't loop forever, and p does that.

stark fable
#

"# "[p<i] is one character shorter than " #"[p==i]

sick hound
#

Haha, it's inverted now

#

But still good

stark fable
#

if you flip around both the string and the p<i/p==i then it won't be inverted

snow beacon
#

Do you need to call complex(a,b)? Can't you do a+b*1j?

#

Oh, brackets around b.

#

Still shorter, I believe.

stark fable
#
abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)
abs(c:=c*c+(y/i-.8+(x/i-.5)*1j)*2.2)```
#

2 characters shorter

sick hound
#

Works

stark fable
#

possibly better if someone figures out how to get rid of some of those brackets

sick hound
#

Is this notation a shorthand for complex numbers in Python?

stark fable
#
>>> complex(0,1)
1j
>>> 1j
1j```
sick hound
#

Ahh okay

snow beacon
#

Could you replace (...-.5)*1j with ...*1j-.5j?

#

One character shorter.

stark fable
#
abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)
abs(c:=c*c+(y/i-.8+(x/i-.5)*1j)*2.2)
abs(c:=c*c+(y/i-.8+x/i*1j-.5j)*2.2)```
#

good spot

#

that should work

#

i think

snow beacon
#

and abs(...)<2 -> and-2<(...)<2

proper vault
#

that abs is of a complex number

snow beacon
#

Oh, curse my assumptions.

harsh canopy
#

Excuse the vulgarity of the source, I'm working with a library called "fuckitpy"
https://hastebin.com/guloxanoge.py
I'm trying to implement a custom codec, and I'm having trouble with what I think is the incremental decoder. The final parameter should be true on the very last call to the incremental decoder's decode method, however it seems to be stuck in a loop calling this method with the final parameter set to true with no data being passed. The codec registers and all the source of the file being run is passed to the decode function, but once it reaches the end of the file it passes nothing forever.

Anyone have any idea how I can sort this out?

formal sandal
sick hound
#
x=y=0;i=50;q=print
while y<i:
 c=p=0;x=-~x%i
 if x==1:q();y+=1
 while p<i and abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)<2:p+=1
 q(" #"[p==i],end=' ')

141 chars now
@sick hound what the fuck

limpid crest
#

@sick hound this is the esoteric python channel, what did you expect? lol

tribal moon
#

I made the fake windows blue screen more realistic

#

it makes the cursor invisible as well as restarts the computer

formal sandal
#

Could you also make it work for Linux? :D

snow beacon
#

Is this shorter? It has slightly different behaviour because it doesn't print a trailing space before newlines.python x=y=0;i=50 while y<i: c=p=0;x=-~x%i;v=x==1;y+=v while p<i and abs(c:=c*c+(y/i-.8+x/i*1j-.5j)*2.2)<2:p+=1 print(" #"[p==i],end=' \n'[v])

#

Looks about 6 shorter.

#

If you want the trailing spaces, though, you can add two characters: end=' \n'[v] -> end=' '+'\n'*v

tribal moon
#

I can make it work for linux

#

but I've never used Linux before

#

so I need to know how it looks like when it has an error

#

What does a Linux version of a BSoD look like?

snow beacon
#

Probably a white-on-black terminal with a lot of text in all caps.

#

No prompt.

tribal moon
#

Is there an image I can see?

#

perhaps a video?

snow beacon
tribal moon
#

Yeah

#

I don't know if anyone knows this, but what is the font in the error terminal thing

modest glade
#

Code page 437 (CCSID 437) is the character set of the original IBM PC (personal computer). It is also known as CP437, OEM-US, OEM 437, PC-8, or DOS Latin US. The set includes all printable ASCII characters, extended codes for accented letters (diacritics), some Greek letters, ...

tribal moon
#

wow.

#

Thanks

#

Well I think I can do it

#

But I don't think I have the time for it

#

maybe I can do it

#

just not in one line

#

and I also can't disguise it as something else

#

I could if I wanted too

hollow patrol
#

Idea: A program that converts python code to much uglier versions

#
if True:
  print(3)

to

while True:
  print(3)
  break
#

and works in multiple steps

#

so you can convert it to one form, then do it again until it's maximum ugly

proper frigate
#

It would be horrible to use, but fun to do lmao

vague hearth
#

i think it should conver to this instead py for _ in range(True): print(3) continue

vestal solstice
#

print(end = '3\n')

thin trout
#

sys.stdout.write('3\n')

sick hound
#

sys.stdout.write("".join([chr(n) for n in [13, 51]]))

thin trout
#

Oh nice one

formal sandal
#

I am deeply confused

thin trout
#

That's the point :D

formal sandal
#

Did you mean

#
sys.stdout.write("".join([chr(n) for n in [13, 52]]))
#

?

thin trout
#

What's the difference?

formal sandal
#

!e

import sys
sys.stdout.write("".join([chr(n) for n in [13, 52]]))
night quarryBOT
#

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

001 | 
002 | 4
formal sandal
#

wtf

#

doesn't work here

thin trout
#

Hmm

formal sandal
gaunt panther
#

is python effecient in small(est sometimes?) bytes for any particular program?

formal sandal
#

what the steaming fuck

thin trout
#

Different encoding perhaps?

formal sandal
#

@gaunt panther What do you mean?

#

!e

import sys
print(sys.stdout)
night quarryBOT
#

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

<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
formal sandal
#

same

thin trout
#

!e
print(ord('4'), ord('2'))

night quarryBOT
#

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

52 50
gaunt panther
#

like you know jelly, it takes very less space to execute something

#

sso how good is python in those cases

spark dock
#

what about me

formal sandal
#

well, Python was not designed as an esoteric language

#

unfortunately

thin trout
#
sys.stdout.write("".join([chr(n) for n in [int(i, base=2) for i in [1101, 110100]]]))```you can throw some binary in there too
#

You could do a PyVM eso language lol

formal sandal
#

Syntax error

thin trout
#

I'm missing a ]

gaunt panther
#

why am i asking here........ how do I install jelly?

formal sandal
#

I've been working a bit on a stack-based language, now I'm writing a VM in C for it, and it's still gonna have a Python frontend (bytecode compiler, maybe REPL)

thin trout
#

If you are going this way, I'd really recommend you to read "the dragon book", it is a book about compiler techniques and stuff, the original python parser (< 3.8) follow this exact implementation

#

It is really technical, but it is great

gaunt panther
#

i wasn't able to find his mention lol

formal sandal
#

Thanks @thin trout , I'll check it out

vestal solstice
gaunt panther
#

wai wha? jelly is writtin in python?

vestal solstice
#

oh, you're asking because you're using windows?

#

yes it's a python program

gaunt panther
#

but how will i type in jelly

vestal solstice
#

I don't actually know how people do that heh

#

I mean you can copy paste by character

gaunt panther
#

lol, i too

#

so i can talk about jelly here ๐Ÿค”

vestal solstice
#

it won;t take long when your programs are short

#

no, it's not python related

gaunt panther
#

yeah, if only I can i can understand jelly, bye, imma take its tutorial

limber orchid
#

I guess this is a 'code golf'-ish question.
Is it possible to go from:

a = some_fun(x)
b = some_fun(y)

to

a, b = some_fun(x,y)
``` in some way?
proper vault
#
a, b = map(some_fun, [x, y])
limber orchid
#

Perfect, I forgot about that, thanks.

marsh void
#
a, b = map(some_fun, (x, y))``` don't waste memory ๐Ÿ‘€
sick hound
#

!e

import sys
sys.stdout.write("".join([chr(n) for n in [13, 52]]))

@formal sandal excuse me why does that not work

marsh void
#

wym

#

!e python import sys sys.stdout.write("".join(map(chr, (13, 52))))

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | 4
marsh void
#

h u h

sick hound
#

that should be 52, 13 but yea

marsh void
#

ah

sick hound
#

unless

#

!e chr(0x52)

marsh void
#

!e python import sys sys.stdout.write("".join(map(chr, (52, 13))))

night quarryBOT
#

@marsh void :white_check_mark: Your eval job has completed with return code 0.

4
marsh void
#

hm

sick hound
#

!e print(chr(52))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

4
marsh void
#

some control character magic?

sick hound
#

!e print(chr(0x52))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

R
sick hound
#

i must have just had the wrong ascii code

#

hm

formal sandal
#

It doesn't work in here, but works in the terminal

sick hound
#

thats.. supposed to say 3

#

i think it should conver to this instead py for _ in range(True): print(3) continue
@vague hearth

#

!eval

import sys
sys.stdout.write("".join([chr(n) for n in [51, 13]]))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

3
marsh void
#
import sys;sys.stdin.write("".join(map(chr,(51,13))))```
#

minified (tm)

proper vault
#

writing to stdin?

sick hound
topaz anchor
#

oh

#

that took some time

#

but I just managed to figure out what was happening

#

so chr(13) is the \r character, and sys.stdout.write returns the amount of chars written
which is why in the terminal/shell you see the 4-2; the 4 is from chr(51) while 2 is from the sys.stdout.write call

tribal moon
#
import sys;sys.stdin.write("".join(map(chr,(51,13))))```

why use semicolons?

sick hound
#

cuz minified

tribal moon
#

do it in one line without semicolons

sick hound
#

huh?

#

teach me, somedude-chan

tribal moon
#

use import

sick hound
#

!eval print(import('sys'))

#

oh.

#

yea

#

im dumb

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

<module 'sys' (built-in)>
sick hound
#

OH

tribal moon
#
__import__('sys').stdin.write("".join(map(chr,(51,13))))```
sick hound
#

stdout

#

but yea

#

you have given me too much power

tribal moon
#

well I'm not the one who wrote it

#

when I do this kind of stuff

#

I usually prefer to put it in lambda functions

#

so instead of py __import__('sys').stdout.write("".join(map(chr,(51,13))))

#

I do py (lambda sys: sys.stdout.write("".join(map(chr,(51,13)))))(__import__('sys'))

sick hound
#

oh.

#

heheh..

sick hound
#

asdsd

#

OH OOPS

#

!e

(lambda ch: list(filter(lambda x: x[0] == ch(str(7772697465)),(lambda y: y.__dict__[ch("6765746d656d62657273")]((lambda x: x.__dict__[ch("7374646f7574")])(__import__(ch(str(737973))))))(__import__(ch("696e7370656374")))))[0][1](ch("68656c6c6f20776f726c642121")))(lambda s: "".join(map(lambda a: chr(int(a, 16)), [s[i * 2:(i + 1) * 2] for i in range((len(s) + 1) // 2)])))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

hello world!!
sick hound
#

:D

neat otter
#

haha nice

sick hound
#

i cant think of any other way to mess with it xD

#

:o wait

stone bane
#

There was a time when I thought hello world was the simplest program in any programming language, it was supposed to be what you started with.

#

No longer. I am now a changed man, my eyes have been opened.

#

goes to find bleach

limpid crest
#

how do I get started on this hell

sick hound
#

oh im not done yet

#

i just discovered you can use builtins with lambdas

#

!e

a = "123"
print(list((lambda x: x(int, a))(map)))
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3]
sick hound
#

and i figured, since i use inspect.getmembers in the code to get write(), why not get __dict__ too

#

how do I get started on this hell
@limpid crest
basically did

list(filter(lambda x: x == "write", inspect.getmembers(sys.stdout)))[0][1]("hello world!!")
limpid crest
#

?

sick hound
#

you asked how to get started, i assumed you meant reading it

limpid crest
#

oh lol

#

well with get started I meant how do I get on this

sick hound
#

ohhh, you want to make hellish code?

limpid crest
#

I wanna get started

#

And idk where to go

#

I'm an intermediate python programmer

#

Or that's how I consider myself

sick hound
#

i mean i just abuse lambda and map

limpid crest
#

okay

sick hound
#

moogs inspired me

limpid crest
#

I can't wait to be able to do this

#
(lambda ch: list(filter(lambda x: x[0] == ch(str(7772697465)),(lambda y: y.__dict__[ch("6765746d656d62657273")]((lambda x: x.__dict__[ch("7374646f7574")])(__import__(ch(str(737973))))))(__import__(ch("696e7370656374")))))[0][1](ch("68656c6c6f20776f726c642121")))(lambda s: "".join(map(lambda a: chr(int(a, 16)), [s[i * 2:(i + 1) * 2] for i in range((len(s) + 1) // 2)]))) ```
sick hound
#

:>

limpid crest
#

:^)

sick hound
#

just a piece at a time

limpid crest
#

To be honest I have no idea what's going on in that code

#

I just know it prints hello world

sick hound
#
import sys
sys.stdout.write("hello!")

__import__("sys").stdout.write("hello!")

(lambda x: x.stdout.write("hello!"))(__import__("sys"))
#

thats evolution ^^^

#

the random character strings/numbers area the hex representations of sys, stdout.. etc

#

ch() converts them to strings

limpid crest
#

okay?

rugged sparrow
#

!e ```py
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})

print(1)
print(1 .repr())```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'py' is not defined
rugged sparrow
#

Ugh mobile

#

!e ```
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})

print(1)
print(1 .repr())```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).

hello world
sick hound
#

segfaults

rugged sparrow
#

Eh it worked mostly

#

I'm replacing the base class of 1 with a custom class

#

!e ```
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})

print(1)```

night quarryBOT
#

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

hello world
rugged sparrow
#

I guess it doesn't like when you access repr directly

limpid crest
#

How do you cause a segfault in python lmao

rugged sparrow
#

Mess with the internals

stark fable
#

!e py __import__('ctypes').string_at(4)

night quarryBOT
#

@stark fable :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
stark fable
#

you can also just do that

tribal moon
#

one line it

hollow patrol
#

someone needs to make a program that makes python longer

#
if True:
  print(3)

to

for _ in range(bool(True)):
    print(3)

to

iterable = iter(range(bool(True)))
try:
    while True:
        _ = next(iterable)
        print(3)
except StopIteration:
    pass
#

and

#
def func(x):
  print(x)
  return x + 1
a = func(1)
b = func(2)

to

print(1)
a = 1 + 1
print(2)
b = 2 + 1
dapper parrot
#

my dad wrote a program that did something like that in the 80s

tribal moon
#

Someone made a program that makes scripts in one line

#

for python

#

I can actually make a script to generate one line code with that website

#

in one line too

hollow patrol
#

@tribal moon That's for Python 2

#

Someone else made it

#

I'm making a Python 3 version

frigid wharf
#

!e ```py
add = lambda x,y:(lambda v:v(x,'add'))(lambda m,l:(list(filter(lambda z:z[0]==l,import('inspect').getmembers(import('ctypes').cast(id(m),import('ctypes').py_object).value)))[0][1]))(y)

print(add(2,7))
print(add(3.2,2.7))

night quarryBOT
#

@frigid wharf :white_check_mark: Your eval job has completed with return code 0.

001 | 9
002 | 5.9
marsh void
#
@func_def(kernel32.OpenProcess)
def open_process(
    access: wintypes.DWORD, inherit_handle: wintypes.BOOL, process_id: wintypes.DWORD
) -> wintypes.HANDLE:
    pass

handle = open_process(access=PROCESS_ALL_ACCESS, inherit_handle=False, process_id=...)
``` improved func_def once again!
#

all these weird positional arguments can now be easily read without opening docs!

tribal moon
#

@hollow patrol That's very impressive! Notify me when you finish

tribal moon
#

I've made the Py2 version so far

#
(lambda requests, code: print(requests.get("http://www.onelinerizer.com/onelineit/", params={'code': code}).content.replace(b'__builtin__', b'builtins')))(__import__('requests'), open(input('Name of python file to oneline: '), 'r+').read())```
#

But I really want to try your Py3 version

#
#

It works for some Python 3 code, because in Python 2, you weren't able to do this py (lambda: print('something'))(), it would give a syntax error, so instead, they did this py (lambda _print: _print('hi'))(__import__('__builtin__').__dict__['print']), but in Python 3, __builtin__ module was renamed to builtins, so this code replaces that with the newer version, so it can work better

(lambda _print: _print('hi'))(__import__('builtins').__dict__['print'])```
tribal moon
#

I mean with the site or the code

#

you can potentially one line almost anything

#
(lambda __g: (lambda __mod: [[[(app.run('127.0.0.1', port=80), None)[1] for __g['hello'] in [(app.route('/')([__func for __func, __func.__name__ in [(lambda : __import__('requests').get('https://www.stackoverflow.com').content, 'hello')]][0]))]][0] for __g['app'] in [(Flask(__name__))]][0] for __g['Flask'] in [(__mod.Flask)]][0])(__import__('flask', __g, __g, ('Flask',), 0)))(globals())
``` like this Flask app that recreates stack overflow
frozen holly
#

im not very good at alot of esoteric stuff, but replace the default sorting algorithm with somthing stupid like bogo sort

tribal moon
#
(lambda random: random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))]))]))])))(__import__('random'))``` Super random
hollow patrol
#

@tribal moon It doesn't work for all cases

tribal moon
#

Your version?

hollow patrol
#

Yep

#

Notable failures: return, try, continue, break, yield

#

global, local, nonlocal

tribal moon
#

try?

#

it can't do error handling?

hollow patrol
#

It's actually tricky

#

So yes, @tribal moon

tribal moon
#

Do you know what contextlib is?

hollow patrol
#

And I can't add in return, continue, or break without try either

#

Yep

#

But contextlib won't work in cases where I need access to the outer scope

#

Like setting a variable in the try and except bodies

tribal moon
#

can onelinerizer do that?

hollow patrol
#

yeah, it might be able to

tribal moon
#

When will you finish this project?

#

I'm actually interested

hollow patrol
#

I'm not sure, it's not my main priority

#

So not for a bit

#

But when I pick it back up I'll work on a scoping generator

#

Which uses dictionaries over :=

tribal moon
#

Well you can use onelinerizer to make onelined code

hollow patrol
#

for python 2

tribal moon
#

It's meant for python 2 code

hollow patrol
#

python 2 is deprecated

tribal moon
#

but can be modified to work for python 3 code

#

by literally just changing one string

hollow patrol
#

not all of it

tribal moon
#

well yeah

hollow patrol
#

try using yield in it

tribal moon
#

really depends on how complex the code it

#

yield won't work

hollow patrol
#

see?

#

that's the problem

#

anyways I'm not working on this for some time

#

I have other projects

tribal moon
#

Please do notify me when you finish

#

This is a very cool project you're doing

dapper parrot
#

you can also one-line anything by just having it get run from a string

sick hound
#

thats cheating

earnest wing
#

Manually forming and compiling an AST? :^)

dapper parrot
#
exec(__import__("zlib").decompress(b"x\x9c]\x8d1\x12\xc3 \x0c\x04{^\xa1P\x99\xb4\xee\xf2\x82< \x1f`la\x98\x01\x89\x91D\x91\xdf\x07'\xaer\xe5\xde\xed\\\x97B\xb6\xf8'\xd6\xca7x\xe5\xa2\xd0\x85\x0f\x89\r\x86\xa2B\x1a\xb4YaR\x88\xb4\x83\xa0\r!P\x8b\x86\r\xc9~\x94-\xa3\xc0\xc6\\g3R\xf2\xc1\xed\x98\xa0\xbdOy\x89r\x84\x87\x83\x99\xcb\x9e\xe0\xbe:\xd7\xbf\xcf\xd7\xc8\xe7\xe2C\xf8\x83\xebI>!\xec6}"))```
sick hound
#
(lambda __g: (lambda __mod: [[[(app.run('127.0.0.1', port=80), None)[1] for __g['hello'] in [(app.route('/')([__func for __func, __func.__name__ in [(lambda : __import__('requests').get('https://www.stackoverflow.com').content, 'hello')]][0]))]][0] for __g['app'] in [(Flask(__name__))]][0] for __g['Flask'] in [(__mod.Flask)]][0])(__import__('flask', __g, __g, ('Flask',), 0)))(globals())
``` like this Flask app that recreates stack overflow

things like this are pretty tho

hollow patrol
#

@dapper parrot @earnest wing Both of those are cheating.

dapper parrot
#

yeah sure

hollow patrol
#

They both involve using multi-line statements indirectly

#

no it is

earnest wing
#

Hence the :^)

tribal moon
#

I think when it comes to one liners, exec and ; would be considered cheating

amber ermine
#

How can I make a keyword? Like, what if I wanted to do print "Hello" in Python 3, how would I make that keyword?

vague gust
#

If anyone wants to suggest challenges feel free to PR them to the challenges directory and if we get an interest I could look into setting up an announcement role for new challenges or something

#

There is a challenge generator in the tools directory for those looking to add challenges

analog dust
#

hey, why do i get a "File not found error" even though the file im trying to open is in the same folder?

whole kiln
analog dust
#

oh okay alright

proper vault
#

@amber ermine you can use #coding: printkw by adding a custom codec

amber ermine
#

@amber ermine you can use #coding: printkw by adding a custom codec
@proper vault Thanks :D I'll look into that

marsh void
#

@vague gust took ya a while huh lemon_thinking

#

but thanks <3

vague gust
#

heh

marsh void
#

I legit forgot I participated in one

#

now that I know much more python than I did back then, time to make more funky stuff :p

#

import ctypes is always a solid start

vague gust
#

lul

sick hound
#

Eval's are stackable: ```py
double_stack = eval('eval("1+1")')
triple_stack = eval('eval("eval(\"1+1\")")')

Is this possible for stacks with more than three evals? I have tried 
```py
quadruple_stack = eval('eval(\"eval(\\"eval(\\\"1+1\\\")\\")\")')
```and ```py
quadruple_stack = eval('eval(\"eval(\\"eval(\\\\"1+1\\\\")\\")\")')

But both of them throw a syntax error. it's really hard to get what's going on with so many strings being parsed.

proper vault
#
In [89]: quadruple_stack = eval(r'eval("eval(\"eval(\\\"1+1\\\")\")")')
```this works
sick hound
#

Ooh, I haven't thought of using raw strings that way

#

Alright, so this works for a stack of five:

quintuple_stack = eval(r'eval("eval(\"eval(\\\"eval(\\\\\\\"1+1\\\\\\\")\\\")\")")')
#

and this for a stack of six hehehe ```py
sextuple_stack = r'eval("eval("eval(\"eval(\\\"eval(\\\\\\\"1+1\\\\\\\")\\\")\")")")'

proper vault
#

made a 20 stack, but paste sites keep crashing

sick hound
#

Hahaha

#

20 stack is over 11000 lines for me

proper vault
#

the file I wrote it is 2MB

#

30 stack was 2G, and I think that was some hard limit rather than the actual size

sick hound
#

Holy hell

#

I think my function is too slow

proper vault
#

it pretty much doubles each iteration

#

because every \ becomes \\

sick hound
#

Yeah, this is how I stack them ```py
def stack_evals(expression, n=10):
slashes = 0
add = 1

s = r""

for _ in range(n):
    s += (r'eval(' + "\\" * slashes) + '"'
    slashes += add
    add *= 2

s += expression

for _ in range(n):
    add //= 2
    slashes -= add
    s += ("\\" * slashes) + '")'


return s
proper vault
#

so 2G may actually be accurate, as it is 1024 times more than 2M

#

ah, I just did

base, res = 'eval({!r})','1+1'
for _ in range(20):
    res = base.format(res)
sick hound
#

Oh, this is good

proper vault
#

could also do

res = '1+1'
for _ in range(20):
    res = f'eval({res!r})'
```to possibly be faster
sick hound
#

!r forces it to be formatted as a raw string by adding escapes?

proper vault
#

it means it uses repr(res) rather than str(res)

sick hound
#

Ahh, okay I understand

#

Awesome solution ๐Ÿ˜„

sick hound
#

The program is just a simple hello world

sick hound
#

how do you write python that is esoteric

#

like the stuff filled with lambdas, etc

#

is there a guide anywhere?

brisk zenith
#

not really. the best thing to do is to take a very simple program and break it down piece by piece until you can write it all as one line for example

dapper parrot
#

does eso include underhanded

snow beacon
#

Certainly.

dapper parrot
#

noice

stark fable
proper vault
#

Where do s,k come from?

stark fable
#
s=lambda a:lambda b:lambda c:a(c)(b(c))
k=lambda a:lambda b:a```
#

the function is also called with the arguments 0, 1, lambda a:lambda b:a+b, and chr

proper vault
#

Interesting

true mortar
#

Has anyone here made a pip package before?

snow beacon
#

forbiddenfruit is up there. Was it made by one of us?

brisk zenith
#

nope :D

wraith galleon
#

I am trying out cython

sick hound
#

OH NO
What did I write?

def add(numbers):
    a = ""
    b = "0"
    c = "number"
    d = "1"
    total = []
    while True:
        e = len(numbers)
        number = numbers[len(a)]
        numbers = numbers[len(b):e]
        while True:
            total.append(c)
            number = number - (int(b) + 1)
            if number == int(b):
                break
        if len(numbers) == len([] * int(b)):
            break
    result = (len(str(total))) / int(d + b)
    print(result)
#

And how does it work?

stone bane
#

What's numbers. Datatype. Also this feels like the wrong room for this, you should take up a help channel instead

snow beacon
teal monolith
#

It looks interesting but also confusing as hell

#

I can't wrap my head around it fully

snow beacon
#

If you've played around with it in another language it's easier to grok.

#

Although all of the stuff about __match__ is indeed incomprehensible.

umbral night
#

Anyone here be able to help me a bit with programmatic access to a decorator that takes parameters?

#

Basically this:


import argparse
from cmd2 import Cmd, with_argparser


p = argparse.ArgumentParser()
p.add_argument('filename')

class TestApp(Cmd):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.do_example = with_argparser(p)(self.do_example)


    def do_example(self, args) -> None:
        self.poutput(f"Argument is: {args.filename}")

    @with_argparser(p)
    def do_example2(self, args) -> None:
        self.poutput(f"Argument is: {args.filename}")

if __name__ == '__main__':
    import sys
    app = TestApp()
    sys.exit(app.cmdloop())```
#

The normal usage is as seen with do_example2. What I'd like is to apply the decorator programmatically as seen in __init__ (as for why, presume I do not have an XY problem ๐Ÿ™‚ )

#

What I get is:

Traceback (most recent call last):
  File "/home/epoulsen/.local/lib/python3.8/site-packages/cmd2/cmd2.py", line 1646, in onecmd_plus_hooks
    stop = self.onecmd(statement, add_to_history=add_to_history)
  File "/home/epoulsen/.local/lib/python3.8/site-packages/cmd2/cmd2.py", line 2075, in onecmd
    stop = func(statement)
TypeError: cmd_wrapper() missing 1 required positional argument: 'statement'
EXCEPTION of type 'TypeError' occurred with message: 'cmd_wrapper() missing 1 required positional argument: 'statement''```
#

The odd part is that example2 is a bound method, as you'd expect, while example is not, so I tried binding it using types.MethodType, but that would yield: EXCEPTION of type 'TypeError' occurred with message: 'do_example() takes 2 positional arguments but 3 were given'

snow beacon
#

Consider looking into MethodType in types.

umbral night
#

๐Ÿ‘

#

Dunno if you read my last message, but I had already tried that.

#

In any case the problem is that do_example is a bound method before doing the decorator in __init__. The solution was to declare do_example as a static method, then using types.MethodType after doing the decoration.

snow beacon
#

Well I thought I had, but apparently not.

hallow hinge
#

One liner for a noughts and crosses game. I found out that list comprehensions are good for replacing while loops as well since you can change the iterator from within. It does pretty much everything you'd expect except win detection.

formal sandal
#

!e

from functools import partial


class InstanceDecorator:
    def __init__(self, wrapper, **kwargs):
        self.wrapper = wrapper
        self.kwargs = kwargs
        self.arg = None

    def __call__(self, fn):
        self.arg = fn
        return self


_BAR_METHODS = []
def bar():
    for method in _BAR_METHODS: method("Bar")



def process_instance_decorators(cls):
    class _Wrapper(cls):
        def __init__(self, *args, **kwargs):
            cls.__init__(self, *args, **kwargs)
            self._apply_instance_decorators()
        
        def _apply_instance_decorators(self):
            for attr_name in dir(self):
                attribute = getattr(self, attr_name)
                if isinstance(attribute, InstanceDecorator):
                    instance_decorator = attribute
                    instance_decorator.wrapper(partial(instance_decorator.arg, self), **instance_decorator.kwargs)
    _Wrapper.__name__ = cls.__name__
    _Wrapper.__qualname__ = cls.__qualname__
    return _Wrapper


@process_instance_decorators
class Foo:
    @InstanceDecorator(_BAR_METHODS.append)
    def hello(self, phrase): print("Foo", phrase)


@process_instance_decorators
class LeftRightPrinter:
    def __init__(self, left): self.left = left

    @InstanceDecorator(_BAR_METHODS.append)
    def world(self, right):
        for i in range(50):
            buf = ""
            if i % 3 == 0: buf += self.left
            if i % 5 == 0: buf += right
            if buf == "": buf += str(i)
            print(buf, end=" ")
        print()

f = Foo()
bar()
g = LeftRightPrinter("Fizz")
bar()
night quarryBOT
#

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

001 | Foo Bar
002 | Foo Bar
003 | FizzBar 1 2 Fizz 4 Bar Fizz 7 8 Fizz Bar 11 Fizz 13 14 FizzBar 16 17 Fizz 19 Bar Fizz 22 23 Fizz Bar 26 Fizz 28 29 FizzBar 31 32 Fizz 34 Bar Fizz 37 38 Fizz Bar 41 Fizz 43 44 FizzBar 46 47 Fizz 49 
formal sandal
#

Problem statement: make a generator run on each instance creation and accept a bound (instance) method instead of running once on a plain function.

#

Is there a better/more flexible/more ugly way of doing this?

eager pond
formal sandal
#

Last time you used that word I had to google it

#

Well, I subscribed to a word-of-the-day service, so my vocabulary will double in 10 years

eager pond
#

hmm what would the metaclass approach look liike

formal sandal
#

Well, that kind of answers Is there a <...> more ugly way of doing this?

eager pond
#

lol

#

hmm its not calling __call__ part of the decorator

formal sandal
#

Post the code here then

#

or in a help channel

eager pond
#
@messenger.event_class
class MessageHandling(BaseService):

    def __init__(self):
        pass
        messenger.subscribe(Events.on_message_recieved, self.on_message_recieved)

    @messenger.EventInstance(messenger.Set(Events.on_message_recieved))
    async def on_message_recieved(self, message) -> None:
        await MessageRepository().add_message(message)
#

def event_class(cls):
    class _Wrapper(cls):
        def __init__(self, *args, **kwargs):
            cls.__init__(self, *args, **kwargs)
            self._apply_instance_decorators()
        
        def _apply_instance_decorators(self):
            for attr_name in dir(self):
                attribute = getattr(self, attr_name)
                if isinstance(attribute, EventInstance):
                    instance_decorator = attribute
                    instance_decorator.wrapper(partial(instance_decorator.arg, self), **instance_decorator.kwargs)
    _Wrapper.__name__ = cls.__name__
    _Wrapper.__qualname__ = cls.__qualname__
    return _Wrapper

class EventInstance:
    def __init__(self, wrapper, **kwargs):
        self.wrapper = wrapper
        self.kwargs = kwargs
        self.arg = None

    def __call__(self, fn):
        self.arg = fn
        return self

class Set():
    def __init__(self, arg):
        self.decor_arg = arg

    def __call__(self, func):
        subscribe(self.decor_arg, func)

        async def wrapper(*args, **kwargs):
            await func(*args, **kwargs)
        return wrapper

#

the init is never run in the event_class decorator

formal sandal
#

How do you instantiate MessageHandling?

#

and why is the messenger.subscribe(Events.on_message_recieved, self.on_message_recieved) in __init__? pass is a no-op, it's not return

eager pond
#
    def load_services(self) -> None:
        log.info('Loading Services')
        #self.load_extension("Cogs.manage_classes")
        for m in ClemBot.walk_modules('services', services):
            for c in ClemBot.walk_types(m, services.base_service.BaseService):
                log.info(f'Loading service: {c.__module__}')
                self.active_services.append(c())```
#

the c()

formal sandal
#

Hm... that's kind of complicated. Is it a private project, or can you share the code?

#

Have you tried stepping in with a debugger?

eager pond
#

i can share ya

#

dynamic cog and service loading in bot/clem_bot.py

formal sandal
#

ok

#

I will debug it with prints, like a real man!

eager pond
#

lol

formal sandal
#

wait, but you commited 6 days ago

eager pond
#

i havent commited the new stuff cuz it doenst work

#

i can commit this stuff on afeauture real fast

formal sandal
#

Well, I can add it if you tell me where to

eager pond
#

and message_handling.py

#

with this

formal sandal
#

By the way, in the later versions of Python you don't need __init__ AFAIK

#

but check the docs on that

eager pond
#

the __init__ pass part?

#

ohh the package modules

#

i was gettign import errors without them

formal sandal
#

What version of python is that?

#

Well, I'm not an expert in that field

eager pond
#

3.7.6 i believe

#

its no problem if you dont wanna deal with getting it up, its not hard to set up but it does take a few mins

#

if you cant tell i have a habit of uhh overengineering ๐Ÿ˜

formal sandal
#

A few minutes? ๐Ÿค”

#

Can I run it without docker?

eager pond
#

well the process of creating a bot token takes like 2 mins

#

yee

#

docker is just for prod

#

i wrote it for beginners to be able to set up easily so its only a few steps

#

you prob dont need to add it to a discord server tbh

formal sandal
#

Well, the invite is invalid anyway

eager pond
#

ohh is it?

#

ohh

#

lol

#

any server will do

#

thats just one i set up to be used by newbies

formal sandal
#
(venv) decorator-factory@df-laptop:~/Python/ClemBot$ python -m bot
2020-06-28 03:52:28,398 INFO Attempting to load BotSecrets.json from /home/decorator-factory/Python/ClemBot
2020-06-28 03:52:28,399 ERROR [Errno 2] No such file or directory: 'BotSecrets.json': The bot could not find your BotSecrets Json File
#

Do i rename that JSON?

eager pond
#

ya

#

put your token in it and rename it

formal sandal
#

yep, works

eager pond
#

thats how i seperate peoples tokens, its gitignored so no one commits it

formal sandal
#
Set constructor is ON!
I'm gonna create an EventInstance with args: <bot.messaging.messenger.Set object at 0x7f863e06ec70> {}
Calling <bot.messaging.messenger.EventInstance object at 0x7f863e06ee80> with fn = <function MessageHandling.on_message_recieved at 0x7f863e071f70>
Let's apply `event_class` to <class 'bot.services.message_handling.MessageHandling'>
#

๐Ÿคท

eager pond
#

it worked?

formal sandal
#

Apparently, yes

#

well, the print statements executed!

eager pond
#

for me

formal sandal
#

hmmm

eager pond
#

ill try printing

formal sandal
#

for me neither

#

wtf

#

We should really move to a help channel

#

I mean, debugging with prints only is kind of esoteric, but you just used breakpoints and ruined everything

eager pond
#

๐Ÿคฃ

sharp night
#

Is that sublime text editor?

formal sandal
#

ye

sharp night
#

How are you using it without paying?

#

I wished it was free.

#

Like fully free.

somber zodiac
#

it is

#

it's an unlimited free trial

#

like winrar

formal sandal
#

yes

#

And, well, I'm not using it anymore.

#

I think using it for writing commercial software actually breaches the argeement.

#

I use VSCode now, and for shorter stuff I use vim or gedit.

somber zodiac
#

fair enough

#

the license is like $100 australian

#

i don't write anything commercial, tho

zenith hare
#

Ascend

#

@somber zodiac

somber zodiac
#

lmao

zenith hare
#

Honestly neovim

#

With built in LSP support

proper vault
#

Doom emacs is also nice

formal sandal
#

I started exploring clojure a little bit, and I tried out emacs. It really is nice

brisk zenith
#

no you're really nice

formal sandal
#

no u

#

you are emacs

brisk zenith
#

:(

formal sandal
#

You don't like being nice?

brisk zenith
#

hm ok u got me there

formal sandal
#

Well, you're going to the Pylag now

brisk zenith
formal sandal
#

the people deserve to know the public enemy

#

anyway, we're getting off topic

brisk zenith
#

oh really? i didn't realise haha

distant wave
#

This syntax looks really strange:

#
>>> a = [((1,),)]
>>> for (i,), in a:
...     print(i)
1
proper vault
#

1 long tuples are a problem with no nice solution

snow beacon
#

There is always the option of pretending that anything that isn't a tuple is a length 1 tuple. (1) is a length 1 tuple, and also equal to 1.

proper vault
#

how do you make ((1,2),) then

snow beacon
#

You would have to ban nesting.

proper vault
#

what about ([1, 2],)[0], if you treat any value as a tuple, what should tuple operations on it do

snow beacon
#

I think you'd not be able to put lists or tuples inside tuples.

proper vault
#

how about custom objects that have __getitem__

#

hell, literally every sequence method would have this problem. What if I have an object with an index method that does something unrelated to tuple.index, what should happen?

snow beacon
#

It would be easier in a strictly typed language, where people would have no hopes that they can use the same indexing method for tuples as for iterables.

tribal moon
#

useless script asks for a message and prints it out

#
(
    lambda __hash__, _str_, __range__, __print__, __input__, __iter__, __next__, __0__, __1__, __self__, __builtins__, __ttp__: (
        lambda int, __main_vars__, ____strings____: __main_vars__[__0__]
        .__getattribute__.__call__(____strings____[__0__])
        .__dict__[__main_vars__[__1__].__qualname__]
        .__call__(
            __import__.__call__(____strings____[__1__])
            .__dict__[__main_vars__[__0__].__name__.__str__.__call__()]
            .__getattribute__.__call__(____strings____[__0__])
            .__dict__[__main_vars__[__1__].__qualname__]
            .__call__(
                int.__call__(
                    __main_vars__[__0__]
                    .__getattribute__.__call__(____strings____[__0__])
                    .__dict__[__main_vars__[(__1__).__add__(__1__)].__qualname__]
                    .__call__(____strings____[(__1__).__add__(__1__)])
                )
            )
        )
    ).__call__(```
#
        __hash__.__getattribute__.__call__(__self__).__dict__[_str_.__qualname__],
        (
            lambda __keywords__: [
                __import__.__call__(__builtins__).__dict__[
                    __hash__.__getattribute__.__call__(__self__)
                    .__dict__[__next__.__qualname__]
                    .__call__(__keywords__)
                    .__qualname__
                ]
                for _ in __hash__.__getattribute__.__call__(__self__)
                .__dict__[__range__.__qualname__]
                .__call__((__1__).__rmul__((__1__).__add__(__1__).__add__(__1__)))
            ]
        )(
            __hash__.__getattribute__.__call__(__self__)
            .__dict__[__iter__.__qualname__]
            .__call__([__hash__, __print__, __input__])
        ),
        (
#
            lambda __strings__: [
                __hash__.__getattribute__.__call__(__self__)
                .__dict__[__next__.__qualname__]
                .__call__(__strings__)
                for _ in __hash__.__getattribute__.__call__(__self__)
                .__dict__[__range__.__qualname__]
                .__call__(((__1__).__rmul__((__1__).__add__((__1__)).__add__((__1__)))))
            ]
        ).__call__(
            __hash__.__getattribute__.__call__(__self__)
            .__dict__[__iter__.__qualname__]
            .__call__([__self__, __builtins__, __ttp__])
        ),
    )
)(
    hash,
    str,
    range,
    print,
    input,
    iter,
    next,
    0,
    1,
    "__self__",
    "builtins",
    "Thing to print: ",
)```
#

obfuscated as much

formal sandal
#

You can replace f() with f.__call__(), .__call__ with .__call__.__call__() and so on by induction.

#

This can improve the unreadability.

earnest wing
#

I like the generous sprinkling of extra underscores on your dunder names.

dapper parrot
#

what the shit is __1__?!

#

oh you defined it

steep mural
#

what the shit is __1__?!
Lol

formal sandal
#

How to transform

@do(T)
def function():
    a = some_expression1
    b = some_expression2
    some_expression3
    some_expression4

into

@do(T)
def function():
    return Monad[T].bind(some_expression1, lambda a: Monad[T].bind(some_expression2,  lambda b: Monad[T].shove(some_expression3, some_expression4))

?

#

Maybe there's some nice way of manipulating the AST?

#

Basically,

var_name = expression
<rest of the code>

should become:

Monad[T].bind(expression, lambda var_name: <rest of the code transformed>)
#

And

expr1
expr2
<rest of the code>

should become:

Monad[T].shove(expr1, Monad[T].shove(expr2, <rest of the code transformed>)

or, if it's any easier:

Monad[T].shove_many(expr1, expr2, <rest of the code transformed>)
rugged sparrow
#

@formal sandal you would probably need to manipulate the code obj

#

Easiest thing would be to loop thru the code obj, extract opcodes and args and build either AST or a source code string then pass that into compile and replace the functions code obj then return it

hardy falcon
#

oh boy visitor patterns

#

flashbacks to compilers

tribal moon
#

script that generates a random string

#

with your choice of length

#
(
    lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________, ___________: __________.join(
        [
            __.__getattribute__.__call__(______)
            .__dict__[_______]
            .__call__(________)
            .choice(
                __.__getattribute__.__call__(______)
                .__dict__[_____.__qualname__]
                .__call__(
                    [
                        *__.__getattribute__.__call__(______)
                        .__dict__[_______]
                        .__call__(_________)
                        .ascii_letters.__add__(
                            __.__getattribute__.__call__(______)
                            .__dict__[_______]
                            .__call__(_________)
                            .digits
                        )
                    ]
                )
            )
            for ____________ in __.__getattribute__.__call__(______)
            .__dict__[_.__qualname__]
            .__call__(
                __.__getattribute__.__call__(______)
                .__dict__[____.__qualname__]
                .__call__(
                    __.__getattribute__.__call__(______)
                    .__dict__[___.__qualname__]
                    .__call__(___________)
                )
            )
        ]
    )
)(
    range,
    hash,
    input,
    int,
    list,
    "__self__",
    "__import__",
    "random",
    "string",
    "",
    "Length of random string: ",
)
sick hound
#

now minify it owo

formal sandal
#

Just imagine how nicely it will fit with structural pattern matching!

proper vault
#

ye, it will be quite wonderful for those kinds of things

#

though due to the lack of typing you can just decide to accept multiple types of objects without a common supertype

formal sandal
#

I hope there'll be no lack of typing ๐Ÿ‘€

halcyon dirge
#

Guys, what are some ways to insanely obfuscate my program, without cutting on speed

proper vault
#

pyarmor I would think

gilded orchid
#

what program would you use for obfuscating without caring about the speed?

proper vault
#

PyArmor anyway probably.

#

maybe graal could do something

thin trout
#

what program would you use for obfuscating without caring about the speed?
I'd use this channel for sure haha

stark fable
#

i just created a version of factorial that only works with numbers up to 5

#
>>> s=lambda a:lambda b:lambda c:a(c)(b(c));k=lambda a:lambda b:a;factorial=lambda a:s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k))((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)(a))(lambda a:a+1)(0)
>>> factorial(1)
1
>>> factorial(2)
2
>>> factorial(3)
6
>>> factorial(4)
24
>>> factorial(5)
120
>>> factorial(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded```
proper vault
#

nice

stark fable
#

s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k)) is the main factorial bit, the rest is conversion to/from church numerals that i couldn't be bothered to SK-ify

rare yarrow
#

Is there a difference between running import os.path and from os import path?

#

I know both do (essentially) the same thing

#

since path is a module we can either import it as a module or a member of os

#

but is there something one will do and not the other?

stone bane
#

No. No diff. Also wrong room

formal sandal
hardy falcon
#

Consider implementing tail recursion, and then tail recursion optimization

#

@formal sandal

formal sandal
#

good idea

#

Well, it's not that hard with normal Python.

#

Hm...

snow beacon
#

Consider also rewriting in Continuation-Passing Style and adding a trampoline at the top level. You might still run out of memory (and it doesn't seem like the easiest thing to rewrite) but that way you wouldn't be using the Python call stack, just storing that information in the continuations.

elfin jungle
#

Can I run python scripts on/with my GPU instead of cpu

snow beacon
#

You might want to ask in a different channel, say #c-extensions or one of the help channels.

modest glade
#

GPUs and CPUs do different things

#

You can use a library like tensorflow to have the GPU do certain tasks, but your program will still run using the CPU

stark fable
#

yep ^

#

if you ran the entire program on the GPU without doing anything else to make it better, it would probably run slower

#

the cases where you can use a GPU to make things faster are rather specific cases and in those cases you'd need special code

formal sandal
thin trout
#

Ooh EBNF parsers lemon_hyperpleased

snow beacon
#

Ironically the grammar library has a spelling error.

brisk zenith
#

haha it does.

formal sandal
#

yep

#

Well, the author isn't a native English speaker, so don't judge!

formal sandal
marsh void
#

oh yes

proper frigate
#

That's my only contribution as well :D
I found an English typo while translating the docs, so I fixed it.

stark fable
#

!e py import __main__ class MyClass: pass a = MyClass() b = MyClass() print(sum(isinstance(getattr(__main__,x),MyClass) for x in dir()))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

2
hard spoke
#

nice, though I think it will fail if loaded as a module

stark fable
#

good point

#

!e py class MyClass: pass a = MyClass() b = MyClass() print(sum(isinstance(getattr(__import__(__name__),x),MyClass) for x in dir()))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

2
stark fable
#

much better

hard spoke
#

...though you can always use eval(__name__) instead of __main__ ๐Ÿ˜„

stark fable
#

!e py print(eval(__name__))

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <module>
004 | NameError: name '__main__' is not defined
stark fable
hard spoke
#

wat

#

why does it work there and not in eval

stark fable
#

!e py print(__main__)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name '__main__' is not defined
stark fable
#

!e py import __main__ print(__main__)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

<module '__main__' (built-in)>
stark fable
#

i imported it

hard spoke
#

oh, I see

stark fable
#

__import__(__name__) works though

distant wave
#

!e ```py
class A:
pass

a = A()
b = A()

import gc
print(gc.get_referrers(A))

night quarryBOT
#

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

[<attribute '__dict__' of 'A' objects>, <attribute '__weakref__' of 'A' objects>, (<class '__main__.A'>, <class 'object'>), <__main__.A object at 0x7fe7da4339d0>, <__main__.A object at 0x7fe7da4090a0>, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'A': <class '__main__.A'>, 'a': <__main__.A object at 0x7fe7da4339d0>, 'b': <__main__.A object at 0x7fe7da4090a0>, 'gc': <module 'gc' (built-in)>}]
hard spoke
#

oh, nice, that's like half the way to a custom garbage collector

stark fable
#

!e ```py
class A:
pass

a = A()
b = A()

import gc
print([x for x in gc.get_objects() if isinstance(x, A)])```

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

[<__main__.A object at 0x7f70fdcef9d0>, <__main__.A object at 0x7f70fdcc50a0>]
vestal hornet
#

Who would've thought my horrible idea would lead to this. Now check if it works across files

distant wave
#

gc.garbage might be interesting too

hard spoke
#

just need to run a thread that does for A in map(eval,dir()):gc.get_referrers(A)

#

and then, uhh

#

clears the memory somehow if there's not any referrers

stark fable
#

exec?

#

!e py a = 'hello' print(exec('a'))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

None
hard spoke
#

yeah, eval of course

stark fable
#

._.

distant wave
#

The only time pythons gc doesn't clear memory is if two things are the case

#

A: there's a reference cycle

#

and B: The objects have an__del__ method

#

From the docs:

#
Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesnโ€™t collect such cycles automatically because, in general, it isnโ€™t possible for Python to guess a safe order in which to run the __del__() methods. 
verbal bane
#

Do any of you know of a keybind that comments out the selected lines?

distant wave
#

You can use DEBUG_SAVEALL to have everything end up in gc.garbage rather than uncollectables, then I guess run your own gc algorithm

#

CTRL-/

#

usually

verbal bane
#

thanks

hard spoke
#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(gc.get_objects())
del lst1
del lst2
gc.collect()
print(gc.get_objects())
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

001 | [{<weakref at 0x7fabeccf9bd0; to 'type' at 0x7fabed53cd80 (frozenset)>}, <weakref at 0x7fabeccf9b80; to 'set' at 0x7fabeccff120>, <built-in method _destroy of weakref object at 0x7fabeccf9b80>, <weakref at 0x7fabeccf9bd0; to 'type' at 0x7fabed53cd80 (frozenset)>, {<weakref at 0x7fabeccf9c70; to 'type' at 0x7fabed53cd80 (frozenset)>}, <weakref at 0x7fabeccf9c20; to 'set' at 0x7fabeccff200>, <built-in method _destroy of weakref object at 0x7fabeccf9c20>, <weakref at 0x7fabeccf9c70; to 'type' at 0x7fabed53cd80 (frozenset)>, (<class 'collections.abc.Set'>,), <function MutableSet.add at 0x7fabeccfaca0>, <function MutableSet.discard at 0x7fabeccfad30>, <function MutableSet.remove at 0x7fabeccfadc0>, <function MutableSet.pop at 0x7fabeccfae50>, <function MutableSet.clear at 0x7fabeccfaee0>, <function MutableSet.__ior__ at 0x7fabeccfaf70>, <function MutableSet.__iand__ at 0x7fabecd01040>, <function MutableSet.__ixor__ at 0x7fabecd010d0>, <function MutableSet.__isub__ at 0x7fabecd01160>, 
... (truncated - too long, too many lines)

Full output: too long to upload

hard spoke
#

huh

#

ah, whoops

stark fable
#

!e py import gc print(len(gc.get_objects()))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

4572
stark fable
#

it's literally every object

#

hmm

#

i wonder

hard spoke
#

let's go with, uhh

#

all lists

stark fable
#

!e py import gc x = gc.get_objects() y = gc.get_objects() print(len(x)) print(len(y))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | 4572
002 | 4573
stark fable
#

LOL

#

!e py import gc x = gc.get_objects() y = gc.get_objects() print(len(x)) print(len(y)) print(x in x) print(y in y) print(x in y) print(y in x)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | 4572
002 | 4573
003 | False
004 | False
005 | True
006 | False
stark fable
#

as expected

hard spoke
#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(list(filter(lambda x:isinstance(x,list),gc.get_objects())))
del lst1
del lst2
gc.collect()
print(list(filter(lambda x:isinstance(x,list),gc.get_objects())))
stark fable
#

the number of objects increases because now there's a reference to a gc.get_objects() result

night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

001 | [['/usr/local', '/usr/local'], [], [], ['/usr/local/lib/python3.8/../LICENSE.txt', '/usr/local/lib/python3.8/../LICENSE', '/usr/local/lib/python3.8/LICENSE.txt', '/usr/local/lib/python3.8/LICENSE', './LICENSE.txt', './LICENSE'], [('.cpython-38-x86_64-linux-gnu.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.abi3.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.py', <class '_frozen_importlib_external.SourceFileLoader'>), ('.pyc', <class '_frozen_importlib_external.SourcelessFileLoader'>)], [('.cpython-38-x86_64-linux-gnu.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.abi3.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.py', <class '_frozen_importlib_external.SourceFileLoader'>), ('.pyc', <class '_frozen_importlib_external.SourcelessFileLoader'>)], ['gc', 'lst1', 'lst2', 'lst
... (truncated - too long)

Full output: too long to upload

hard spoke
#

argh

#

let's go with, uhh

#

lst in name

stark fable
#

name?

#

where are you going to get a name from?

#

it's just a list of values

hard spoke
#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(list(filter(lambda x:"lst" in str(x),gc.get_objects())))
del lst1
del lst2
gc.collect()
print(list(filter(lambda x:"lst" in str(x),gc.get_objects())))
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

001 | [['gc', 'lst1', 'lst2', 'lst1', 'lst1', 'append', 'lst2', 'print', 'list', 'filter', 'x', 'str', 'x', 'lst', 'gc', 'get_objects', 'lst1', 'lst2', 'gc', 'collect', 'print', 'list', 'filter', 'x', 'str', 'x', 'lst', 'gc', 'get_objects'], (None, 'lst'), ('gc', 'lst1', 'lst2', 'append', 'print', 'list', 'filter', 'get_objects', 'collect'), {'__repr__': <slot wrapper '__repr__' of 'bytearray' objects>, '__str__': <slot wrapper '__str__' of 'bytearray' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'bytearray' objects>, '__lt__': <slot wrapper '__lt__' of 'bytearray' objects>, '__le__': <slot wrapper '__le__' of 'bytearray' objects>, '__eq__': <slot wrapper '__eq__' of 'bytearray' objects>, '__ne__': <slot wrapper '__ne__' of 'bytearray' objects>, '__gt__': <slot wrapper '__gt__' of 'bytearray' objects>, '__ge__': <slot wrapper '__ge__' of 'bytearray' objects>, '__iter__': <slot wrapper '__iter__' of 'bytearray' objects>, '__init__': <slot wrapper '__init__' of 'byte
... (truncated - too long, too many lines)

Full output: too long to upload

hard spoke
#

far, far too many objects

stark fable
#

!e py import gc lst1 = [] print(str(lst1)) print('lst' in str(lst1))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | []
002 | False
stark fable
#

._.

distant wave
#

!e ```py
import gc
lst1 = []
print(repr(lst1))
print('lst' in repr(lst1))

night quarryBOT
#

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

001 | []
002 | False
hard spoke
#

sure, but when printing the output of gc.get_objects(), they do have variable names

stark fable
#

no they don't

#

!e py import gc lst = [] x = gc.get_objects() print(lst in x)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

True
stark fable
#

the list is in gc.get_objects()

#

!e py import gc print(type(gc.get_objects())) print(type(gc.get_objects()) is list)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | <class 'list'>
002 | True
hard spoke
#

So why do I get results when I filter for "lst" in str(x)?

stark fable
#

as you can see gc.get_objects() is just a normal list

#

you get results because some of the objects that the GC is tracking are tuples or lists that contain the word lst

#

lst1 does not contain lst but something like __main__.__dict__ does

#

!e py import __main__ lst1 = [] print(__main__.__dict__)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__main__': <module '__main__' (built-in)>, 'lst1': []}
hard spoke
#

sure, and since I want to check if there are still references to it, it works

stark fable
#

!e py import __main__ import gc lst1 = [] print('lst' in str(__main__.__dict__)) print(__main__.__dict__ in gc.get_objects())

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
stark fable
#

ok the issue with doing that is

#

!e py import gc x = ['lst'] print(x in gc.get_objects()) print('lst' in str(x))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
hard spoke
#

hmm

vestal hornet
#

If eval gets disabled again, I'm blaming you lot ๐Ÿ˜›

stark fable
#

well this isn't an actual security vulnerability in the bot

#

it's just messing with python

#

i don't see why they would disable eval just because of some people doing weird stuff in the weird stuff channel

hard spoke
#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = gc.get_objects()
del lst1
del lst2
gc.collect()
res2 = gc.get_objects()
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
night quarryBOT
#

@hard spoke :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 10, in <module>
003 |   File "<string>", line 10, in <listcomp>
004 | RecursionError: maximum recursion depth exceeded in comparison
hard spoke
#

oh

#

I have never seen this before.

stark fable
#

!e py lst = [] lst.append(lst) print(lst == lst)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

True
stark fable
#

oh

#

huh

#

oh

#

!e py x = [] x.append(x) y = [] y.append(y) print(x == y)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | RecursionError: maximum recursion depth exceeded in comparison
stark fable
#

@hard spoke there ^

vestal hornet
#

It was a bit of a joke ๐Ÿ˜„

hard spoke
#

wow, that's a lot of things one can break with a simple pointer loop

#

so I can't even compare that list to itself

#

yikes

#

...can I calculate its hash?

vestal hornet
#

Someone wanna explain what happened there?

stark fable
#

x and y are two lists and they both have one element

#

so to determine if they're equal, you look at whether the elements are equal

#

so you compare x[0] (x) and y[0] (y)

#

so now, 1 level of recursion deeper, you're checking if x and y are equal

hard spoke
#

!e

lst1 = []
lst2 = (lst1,)
lst1.append(lst2)
#print(lst1==lst2)
print(hash(lst2))
stark fable
#

this continues until it goes too far and you get an exception

hard spoke
#

right...

vestal hornet
#

Ahh

night quarryBOT
#

@hard spoke :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | TypeError: unhashable type: 'list'
vestal hornet
#

What if you make a copy instead?

hard spoke
#

argh, won't work with tuples, and lists aren't hashable anyway

stark fable
#

something to do with is/id might work

#

since that doesn't require actual comparison

#

hang on a second

#
res1 = gc.get_objects()
del lst1
del lst2
gc.collect()
res2 = gc.get_objects()
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])```
#

how can res1 contain anything that res2 doesn't

#

res1 holds references to all of those things

hard spoke
#

well, I ran gc.collect()

#

so my hope is that the two lists will be gone

stark fable
#

why would they be collected

#

they were referenced by res1

hard spoke
#

ooh

rugged sparrow
#

you could force an object to be collected if you really want to

stark fable
#

!e py import gc x = [] y = [x] del x gc.collect() lst = gc.get_objects() x = y[0] print(x in lst)

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

True
hard spoke
#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

001 | New: ['<function <listcomp> at 0x7fbe18179d30>', "{'Py_Repr': [{...}, [...]]}", "{'__name__': '_locale', '__doc__': 'Support for POSIX locales.', '__package__': None, '__loader__': None, '__spec__': None, 'setlocale': <built-in function setlocale>, 'localeconv': <built-in function localeconv>, 'strcoll': <built-in function strcoll>, 'strxfrm': <built-in function strxfrm>, 'nl_langinfo': <built-in function nl_langinfo>, 'gettext': <built-in function gettext>, 'dgettext': <built-in function dgettext>, 'dcgettext': <built-in function dcgettext>, 'textdomain': <built-in function textdomain>, 'bindtextdomain': <built-in function bindtextdomain>, 'bind_textdomain_codeset': <built-in function bind_textdomain_codeset>, 'LC_CTYPE': 0, 'LC_TIME': 2, 'LC_COLLATE': 3, 'LC_MONETARY': 4, 'LC_MESSAGES': 5, 'LC_NUMERIC': 1, 'LC_ALL': 6, 'CHAR_MAX': 127, 'Error': <class 'locale.Error'>, 'DAY_1': 131079, 'DAY_2': 131080, 'DAY_3': 131081, 'DAY_4': 131082, 'DAY_5': 131083, 'DAY_6': 131084, 'DAY_7': 
... (truncated - too long)

Full output: too long to upload

hard spoke
#

hmm, interesting

#

!e

import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Deleted: ["('_mapping',)", '(<object object at 0x7f5132f65150>,)', "(<class 'object'>,)", '(None,)', "('name', 'eof')", "('self', 'name', 'eof')", "(None, 'Use %s() or %s to exit')", "('self',)", "('sys', 'stdin', 'close', 'SystemExit')", "('self', 'code')", '(None,)', '(None, 0, <code object <listcomp> at 0x7f5132f20ea0, file "/usr/local/lib/python3.8/_sitebuiltins.py", line 40>, \'_Printer.__init__.<locals>.<listcomp>\')', "('path', 'join')", "('.0', 'dir', 'filename')", "('files', 'os')", "('os', '_Printer__name', '_Printer__data', '_Printer__lines', '_Printer__filenames')", "('self', 'name', 'data', 'files', 'dirs')", "(None, 'r', '\\n')", "('_Printer__lines', '_Printer__filenames', 'open', 'read', 'OSError', '_Printer__data', 'split', 'len', '_Printer__linecnt')", "('self', 'data', 'filename', 'fp')", "(None, '\\n', 'Type %s() to see the full %s text', 2)", "('_Printer__setup', 'len', '_Printer__lines', 'MAXLINES', 'join', '_Printer__name')", "('', 'q')", "('_Printer__setup', 'ran
... (truncated - too long)

Full output: too long to upload

hard spoke
#

...and if I run gc.collect() immediately on start?..

#

!e

import gc
gc.collect()
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Deleted: ['[[[...]]]', '[[[...]]]', "(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')", "{139752179003424: <weakref at 0x7f1a9688bdb0; to 'type' at 0x7f1a96fc7020 (TypeError)>, 139752179002976: <weakref at 0x7f1a9688bef0; to 'type' at 0x7f1a96fc6e60 (StopAsyncIteration)>, 139752179002464: <weakref at 0x7f1a9688d040; to 'type' at 0x7f1a96fc6c60 (StopIteration)>, 139752179000384: <weakref at 0x7f1a9688d4f0; to 'type' at 0x7f1a96fc6440 (ImportError)>, 139752178999136: <weakref at 0x7f1a9688d860; to 'type' at 0x7f1a96fc5f60 (OSError)>, 139752178991968: <weakref at 0x7f1a9688d9f0; to 'type' at 0x7f1a96fc4360 (EOFError)>, 139752178991520: <weakref at 0x7f1a9688db80; to 'type' at 0x7f1a96fc41a0 (RuntimeError)>, 139752178990176: <weakref at 0x7f1a96890040; to 'type' at 0x7f1a96fc3c60 (NameError)>, 139752178989280: <weakref at 0x7f1a96890310; to 'type' at 0x7f1a96fc38e0 (AttributeError)>, 139752178988576: <weakref at 0x7f1a968904a0; to 'type' at 0x7f1a96fc3620 (Synt
... (truncated - too long)

Full output: too long to upload

hard spoke
#

that's a lot of weird stuff

stark fable
#

a lot of seemingly random things are going to change just because the interpreter is running

#

those are probably all either internal interpreter things or parts of the program you don't recognize

hard spoke
#

(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')
I wonder what that tuple is ๐Ÿ˜„

#

and why is it only collected on the second collect

stark fable
#

idk

hard spoke
#

!e

import gc
gc.collect()
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
gc.collect()
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",str([x for x in res1 if x not in res2])[:1000])
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Deleted: ['[[[...]]]', '[[[...]]]', "(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')", "{140590596575264: <weakref at 0x7fddcc1d9db0; to 'type' at 0x7fddcc915020 (TypeError)>, 140590596574816: <weakref at 0x7fddcc1d9ef0; to 'type' at 0x7fddcc914e60 (StopAsyncIteration)>, 140590596574304: <weakref at 0x7fddcc1db040; to 'type' at 0x7fddcc914c60 (StopIteration)>, 140590596572224: <weakref at 0x7fddcc1db4f0; to 'type' at 0x7fddcc914440 (ImportError)>, 140590596570976: <weakref at 0x7fddcc1db860; to 'type' at 0x7fddcc913f60 (OSError)>, 140590596563808: <weakref at 0x7fddcc1db9f0; to 'type' at 0x7fddcc912360 (EOFError)>, 140590596563360: <weakref at 0x7fddcc1dbb80; to 'type' at 0x7fddcc9121a0 (RuntimeError)>, 140590596562016: <weakref at 0x7fddcc1de040; to 'type' at 0x7fddcc911c60 (NameError)>, 140590596561120: <weakref at 0x7fddcc1de310; to 'type' at 0x7fddcc9118e0 (AttributeError)>, 140590596560416: <weakref at 0x7fddcc1de4a0; to 'type' at 0x7fddcc911620 (Synt
... (truncated - too long)

Full output: too long to upload

hard spoke
#

what

#

500 symbols is short enough to show, but 1000 is too long to upload? ๐Ÿค”

stark fable
#

maybe somewhere between 500 and 1000 is something ridiculously long

hard spoke
#

nah, I'm truncating the string, not the list

stark fable
#

oh

#

huh

hard spoke
#

so the reason is probably that it's limited by lines and by symbols

#

normally "too big to show" outputs have far less chars per line than this ๐Ÿ˜›

fiery hare
#

Can one manually change the class that an instance belongs to?

#

I want to do a terrible thing

brisk zenith
#

yeah just override __class__

#

like, x.__class__ = another_class

fiery hare
#

I thought that was protected

brisk zenith
#

for builtin types, yeah

fiery hare
#

!e

class A: pass
class B: pass

a = A()
a.__class__ = B
print(a)
night quarryBOT
#

@fiery hare :white_check_mark: Your eval job has completed with return code 0.

<__main__.B object at 0x7f5e19f549d0>
brisk zenith
#

:D

fiery hare
#

:O

brisk zenith
#

it's actually given as a note on some page of the fluent python book

fiery hare
#

I'm trying to manually change the type of a function though.

proper vault
#

You just cannot do a.__class__ = int

brisk zenith
#

it says it's a horrible idea but technically possible

livid gorge
#

so how does this !e work

#

where's it executed

fiery hare
#

That might be documented on our github. It's called snekbot or something

livid gorge
#

ah

fiery hare
#

Skekbox?

proper vault
#

Snekbox iirc

fiery hare
#

Yeeeee

proper vault
#

You cannot assign class on instances of builtins afaik

fiery hare
#

Anyway I'm trying to implement function composition for the lulz

#

It should be doable with lambdas if you can subclass the function class and make instances of it. But I can't find a way to do that.

livid gorge
#

I wrote something kinda similar but instead of sending a script it's like an interactive console

fiery hare
#

I'm not sure how that could be similar

livid gorge
#

oh sorry, I meant similar to snekbox ๐Ÿ˜„

fiery hare
#

This would be (range @ len)(8) being equivalent to range(len(8))

#

Which is a terrible thing because range len is virtually always wrong.

#

Also doesn't make sense because 8 doesn't have a len.

livid gorge
#

I clarified

proper vault
#

I think you would need to forbiddenfruit matmul of function

fiery hare
#

What's that?

proper vault
#

!e has it, but it seems to not work 100%

fiery hare
#

That's cool, I'll have to see how they did it.

thin trout
#

It is supposed to work in snekbox lemon_unamused

#

You can fill an issue if it doesn't I guess

thin trout
#

Ah, that's a forbidden fruit issue

#

Maybe we should try with the latest version

lone granite
#

Would implementing a ReusedIteratorError exception break functions that expect iterators and don't do weird things?

#

Say I make an iterator that raises StopIteration the first time you call next on it, but the second time it raises ReusedIteratorError

#

I find myself fixing errors related to reusing iterators quite often

#

hmmm

#

I think I could even wrap iterators with something that does that

#

Hmm

#

This might break things like queue iterators

#

or async stuff

lone granite
#

oh interesting

#

generators are assumed to never be called again after StopIteration from what I can see

lone granite
#
#!/usr/bin/env python3.8
from typing import TypeVar, Iterator

class IteratorExhaustedError(Exception):
    """Exception raised when exhausted iterators are ``next``d"""

T = TypeVar("T")
class reuse_guard(Iterator[T]):
    """
    Wraps an iterator so that StopIteration is only raised once,
    after that, ``IteratorExhaustedError`` will be raised to detect
    fixed-size iterator misuses
    """
    def __init__(self, iterator: Iterator[T]):
        self._iterated: bool = False
        self._iterator = iterator

    def __next__(self) -> T:
        try:
            return next(self._iterator)
        except StopIteration as e:
            if self._iterated:
                raise IteratorExhaustedError(
                    "This iterator has already reached its end")
            self._iterated = True
            raise e
    
    def __iter__(self) -> Iterator[T]:
        return self
bleak quest
#

Hi everyone. For the project that I'm working on I need to use a bulk email verifier. do you know any python libraries than can do that? I looked for some projects on github but wasn't able to get them to work.

viscid tulip
grim geyser
#

@bleak quest what do you mean by email verifier, specifically?

#

I would say that it's off topic but, heck, emails are esoteric things so why not

#

are you verifying the email addresses specifically? because if so there's no real good pattern

bleak quest
#

so the process is like this

#

I have names of people and their domain

#

I would create a list of common possible emails such as: firstname.lastname@<theirdomain> lastname.firstname@<theirdomain> and etc.

#

this part is not a problem

grim geyser
#

mm

bleak quest
#

then I have to use a tool to verify these one by one

grim geyser
#

not-- necessarily the best idea always btw

#

if you're making new email accounts that is

bleak quest
#

this is how email guesser/finders usually work

grim geyser
#

ahh, I see now

#

hmm

bleak quest
#

so the last step is a tricky one. since verification process requires SMTP handshake

#

it for sure takes time to code it

grim geyser
#

okay that might be vaguely unethical so I feel iffy :p

#

but yes

#

you have to connect; there's no way about detecting account existence

#

it's entirely internal

#

what specifically are you verifying, with a SMTP handshake?

bleak quest
#

If the email account is working

grim geyser
#

ahh I think I see

proper frigate
#

there are websites out there doing that, so it must be guaranteed by SMTP

bleak quest
#

yeah

#

I read about it. they use SMTP

grim geyser
#

not entirely familiar with SMTP myself but I imagine #networks might have a bit more general knowledge for APIs to that

bleak quest
#

the point is I need this tool to be integrated in my software

#

the websites are usually premium

grim geyser
#

let me check if smtplib will cover this

bleak quest
#

not entirely familiar with SMTP myself but I imagine #networks might have a bit more general knowledge for APIs to that
@grim geyser awesome

#

I will message there

#

let me check if smtplib will cover this
@grim geyser Thnx

grim geyser
#

that miight help

bleak quest
#

thanks

#

seems complicated thought ๐Ÿ˜„

#

will study it I guess

grim geyser
#

ehhh, I'm not familiar with SMTP but it's mostly just basic words

#

HELO seems like a, well, "hello"

#

there's also EHLO so something's funky, though :p

bleak quest
#

that's interesting

grim geyser
#

-ah, that's extended HELO for what I can assume is extended SMTP

#

hope that helps!

bleak quest
#

you helped a lot. thanks

#

I will look into it

limpid crest
#

how to clear the terminal screen in a chad way

(lambda __m, __s: __import__.__call__.__call__.__call__(__m).system.__call__.__call__.__call__(__s))("os", "cls" if __import__("sys").platform == "win32" else "clear")```
#

made by me :p

brisk zenith
#

__call__.__call__.__call__ is a little too redundant haha

#

why not do "win32".__str__() while you're at it? :^)

hard spoke
#

exec("".join(['(lambda __m, __s: __import__'] + ['.__call__']*100 + '(__m).system' + ['.__call__']*100 + '(__s))("os", "cls" if __import__("sys").platform == "win32" else "clear")'))

๐Ÿ™‚

snow beacon
#

You could put all the letters you need into a single string and index it to make your strings.

hard spoke
#

If you do it, you can then use a genetic algorithm or some other metaheuritic to figure out a way to clear the terminal or some other task in the shortest possible way ๐Ÿ™‚

stark fable
#

import os;os.system(['clear','cls'][os.sys.platform=='win32']) is pretty short

grim geyser
#

why not

#

make the AST of the code first

#

then pickle and unpickle it

#

and then run it to clear the screen

stark fable
#

...can you unpickle ast?

grim geyser
#

oh absolutelt

#

well

#

not sure about natively but it should be easily made picklable

stark fable
#

checks it works

grim geyser
#

wait, really?

#

oh my

#

this has many opportunities for one of my projects now ๐Ÿ‘€

stark fable
#
>>> import ast
>>> import pickle
>>> ast.parse('import os; print("hello world!")')
<_ast.Module object at 0x0000011C8544CB00>
>>> pickle.dumps(_)
b'\x80\x03c_ast\nModule\nq\x00)Rq\x01}q\x02X\x04\x00\x00\x00bodyq\x03]q\x04(c_ast\nImport\nq\x05)Rq\x06}q\x07(X\x05\x00\x00\x00namesq\x08]q\tc_ast\nalias\nq\n)Rq\x0b}q\x0c(X\x04\x00\x00\x00nameq\rX\x02\x00\x00\x00osq\x0eX\x06\x00\x00\x00asnameq\x0fNubaX\x06\x00\x00\x00linenoq\x10K\x01X\n\x00\x00\x00col_offsetq\x11K\x00ubc_ast\nExpr\nq\x12)Rq\x13}q\x14(X\x05\x00\x00\x00valueq\x15c_ast\nCall\nq\x16)Rq\x17}q\x18(X\x04\x00\x00\x00funcq\x19c_ast\nName\nq\x1a)Rq\x1b}q\x1c(X\x02\x00\x00\x00idq\x1dX\x05\x00\x00\x00printq\x1eX\x03\x00\x00\x00ctxq\x1fc_ast\nLoad\nq )Rq!}q"bh\x10K\x01h\x11K\x0bubX\x04\x00\x00\x00argsq#]q$c_ast\nStr\nq%)Rq&}q\'(X\x01\x00\x00\x00sq(X\x0c\x00\x00\x00hello world!q)h\x10K\x01h\x11K\x11ubaX\x08\x00\x00\x00keywordsq*]q+h\x10K\x01h\x11K\x0bubh\x10K\x01h\x11K\x0bubesb.'
>>> pickle.loads(_)
<_ast.Module object at 0x0000011C8544CB00>
>>> compile(_, '<idk>', 'exec')
<code object <module> at 0x0000011C85429420, file "<idk>", line 1>
>>> exec(_)
hello world!```
grim geyser
#

well huh

#

that brings a tear to my eye

#

and a LISP-shaped desire in my heart ahaha

dusty haven
#

You can also use marshal to serialize and deserialize the code object itself

#

Bypassing the need for an AST object anywhere

#

s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k)) is the main factorial bit, the rest is conversion to/from church numerals that i couldn't be bothered to SK-ify
Beautiful, love the SKI calculus.

stark fable
#

technically that's just the SK calculus

#

instead of I i used s(k)(k)

#

they're equivalent (SKKx = Kx(Kx) = x = Ix, therefore SKK = I)

halcyon dirge
#

Guys, I had a doubt

#

I made a PyGtk Calculator at

#

Can we obfuscate it

#

Without impacting the speed ?

#

๐Ÿ˜ƒ

quasi geyser
#

given it's just doing basic operations, rendering the elements is the bulk of the performance hit

halcyon dirge
#

Yes.............But its the only way I found

#

It uses like 26mb ram

#

from terminal

#

|| Gnome-calculator uses 22 mb ram + thousands of more features ||

#

Can anyone help ?

#

The entrie source code is about 187 lines including comments and newlines and about 150 with just real code

#

If I post that much here, It will get too long

night quarryBOT
halcyon dirge
quasi geyser
#

what do you mean by obfuscating it

#

the source code itself?

#

or what

dusty haven
#

technically that's just the SK calculus
Well yes, but for some reason most sites list it as SKI

#

I don't think there's actually any combinator calculus or lambda calculus at all (typed or untyped) where you have a non-functionally complete subset of operators that becomes functionally complete iff identity is added

halcyon dirge
#

what do you mean by obfuscating it
@quasi geyser I meant the source code.

quasi geyser
#

i guees you could base64 it, but that won't really fool anyone

#

don't know why you would want to obfuscate this

proper vault
#

pyArmor can be used to obfuscate python source

haughty halo
#

@lofty prawn your spotify playlist isn't something for this channel

halcyon dirge
#

[ Linux ] When ever you guys need to shut your system down, just do it

#
python -c "(lambda x: __import__.__call__.__call__.call__.__call__(x))('os').system.__call__.__call__('shutdown ' + str(__import__.__call__('math').sqrt(4) - 2))"```
dusty haven
#

LOL

#

||You might also be able to further obfuscate the 0 with some mixed-boolean arithmetic or similar bitwise meet||

sick hound
#

[ Linux ] When ever you guys need to shut your system down, just do it
@halcyon dirge
For windows

exec(''.join(chr(x) for x in [105, 109, 112, 111, 114, 116, 32, 111, 115, 59, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 39, 115, 104, 117, 116, 100, 111, 119, 110, 32, 47, 115, 39, 41]))
thin trout
#

Well to be fair, it is pretty easy to un-obfuscate

halcyon dirge
#

[ Very hysterical laughter ]

halcyon dirge
#

I have a venigere cipher module ( Which i made on my own ) and I will cipher my string format of the code using that and then execute it in a exec.

neat holly
#

Speaking of those challenges

#

tho i still need todo the auto fill

whole light
#

Hello! I'm working with a Settings class, where there is a default template that firstly exists in a json file, which is then loaded into memory (a dict) once the program starts. This data will then be thrown into the Settings every time an object is created.

This is only the default, so it also checks in redis if there has been any manual changes (all manual setting changes will be accessible from redis).
If it finds a value that has been change, I simply overwrite said dictionary key with a new value in the same Settings object.

I've just now realized that since I first retrieve the "default settings", I just pass a reference to those default settings to the Settings object, so whenever I overwrite it with the manually changed settings, the "default settings" changes too.

#

What I want I assume is a copy of the "default settings" dict instead, or is there any other preferred method?

#

Any tips are appreciated

modest glade
#

settings = default.copy()

#

Or settings = dict(default)

#

If you have mutable objects in the dict though then you need a deep copy

#
import copy
settings = copy.deepcopy(default)
thin trout
#

.copy() will be faster though

#

It is just a memcopy while dict() will create a new object and populate it

sage oxide
#

i was looking at the esoteric challenges, they looked really fun, alhough quite confidential

snow beacon
#

Confidential?

sage oxide
#

given the number of answers out of the number of members, even at the time, yes I think it can be qualified as confidential

snow beacon
#

Perhaps a better word is 'esoteric'.

sage oxide
#

I meant confidential in popularity

snow beacon
#

I've never heard the word used that way.

#

But yes, we don't get many 'round these parts.

sick hound
zenith hare
#

Let's say that you have a variable a = list() and b = dict() and you want to store both of them inside a class. How many of you would inherit from dict or list and store the other one as self.a = list() self.b = dict() ?

#

I think this is idiotic and leads to complex code, any hot takes?

grizzled cloak
#

Inheriting is when you want the behavior of the parent class, no reason to do it here

#

As far as I can see

brisk zenith
#

yeah that example makes very little sense to me, at least without some context to possibly justify that haha

amber ermine
#

How do I do what I am trying to do (thimk)?
f'Shortened word: {ip[:minimum_value(len(word) - 1, 4)] + '...' if minimum_value(len(word) - 1, 4) != len(word) - 1 else word}?'

#

If it is longer than 5 characters it should add ..., if it is five or less characters it should show just the word

hard spoke
#

!e

word = "stratification"
MAX_WORD_LEN = 5
res = f"Shortened word: {word if len(word)<=MAX_WORD_LEN else word[:MAX_WORD_LEN]+'...'}"
print(res)
#

Like this?

night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Shortened word: strat...
hard spoke
#

you're doing far too much weird stuff with mins, unless that's intentionally esoteric ๐Ÿ˜›

amber ermine
#

Haha, no I tried to make it normally but kept having to redo it until it became esoteric. Thanks for the help lol

hard spoke
#

๐Ÿ‘Œ

amber ermine
#

Welp, also just learned that my original was messed up because I did ' instead of "

formal sandal
#

Actually, that's the wrong way of shortening a word!

#

a little gotcha

hard spoke
#

oh, I knew someone would come to make this more channel-fitting ๐Ÿ˜›

formal sandal
#

If you 'shorten' a word with 6 or 7 letters this way, you'll end up with a longer word

hard spoke
#

ah, fair enough

steep crest
#

i wrote a word lenghtner confused reptile

hard spoke
#

!e

word = "apeiron"
MAX_WORD_LEN = 5
res = f"Shortened word: {word if len(word)<=MAX_WORD_LEN+2 else word[:MAX_WORD_LEN]+'...'}"
print(res)
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Shortened word: apeiron
steep crest
#

i didnt read properly

upbeat lynx
#

hi guys

#

what is decorators??

#

can anyone explain it to me??

formal sandal
sick hound
#

@sick hound

#

i just run that obfuscated code