#esoteric-python

1 messages ยท Page 145 of 1

icy wing
#

Whats with the [-1] index at the end?

#

Oh, right

#

you create a tuple

#

you are returning the sum part

#

got it

sly root
#
f=lambda _0,_1=0:((_2:=len(_0),[[[0for(_1)in[_1+(None,1)[_0[_3]+_0[_4]in _0]]]for(_4)in range(_3+1,_2)]]for(_3)in range(_2)],_1)[-1]```
#

but idk if it works

earnest wing
#

Also, len(aaa for bbb in ccc if ddd) => sum(ddd for bbb in ccc)

#

useful golf a lot of the time

severe canyon
#

my take:

f=lambda w:sum(w[i]+w[j]in w for i in range(len(w))for j in range(i+1,len(w)))
quartz wave
severe canyon
#

u right

#

i tried to get an elegant solution like:

g=lambda n:len({map(sum,combinations(n,2))}&{*n})
from itertools import*

but i realized you need to account for duplicates

sick hound
#

its all about magic methods?

sleek flume
#

My variant without set() optimization:

f = lambda w: sum(n+m in w for i, n in enumerate(w) for m in w[i+1:])```
with it (almost 20x faster on 250 numbers input):
```python
f = lambda w: (s:=set(w), sum(n+m in s for i, n in enumerate(w) for m in w[i+1:]))[1]```
floral meteor
quartz wave
royal coral
#

Could someone tell me where I can get more information about the __code__ dunder?

quartz wave
#

!e ```py
from pydoc import help
help((lambda:0).code)

night quarryBOT
#

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

001 | Help on code object:
002 | 
003 | class code(object)
004 |  |  code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, linetable, freevars=(), cellvars=(), /)
005 |  |  
006 |  |  Create a code object.  Not for the faint of heart.
007 |  |  
008 |  |  Methods defined here:
009 |  |  
010 |  |  __eq__(self, value, /)
011 |  |      Return self==value.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/mahetarawo.txt?noredirect

floral meteor
#

Lol just...

#

!e print((lambda:0).code.doc)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Create a code object.  Not for the faint of heart.
maiden vine
#

Aight y'all

#

Hit me with something horrifying XD

quartz wave
night quarryBOT
#

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

\\\''\\'\\\\'''''
maiden vine
#

I'm not sure what I'm looking at

sick hound
wheat river
#

!e

s='s=%r;print(s%%s)';print(s%s)

night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

s='s=%r;print(s%%s)';print(s%s)
near gust
#

So I've been naming myself python magic methods in a server and then telling facts about them. Here's how it went so far: tohnk

quartz wave
#

works on windows if you modify cpython for it

near gust
#

that's actually really cool

#

specifically I didn't know __setstate__ existed

fair quartz
fair quartz
#

oh its for pickle ok

near gust
fair quartz
#

sounds good

#

now __prepare__ for trouble

#

4gb of ram

floral meteor
wheat river
floral meteor
#

I "grew up" on IDLE and now use notepad++

#

pycharm I only pull out if I wanna contribute to someone else's project

sick hound
#

I started out that way and learned with vim and smaller editors like kwrite/kate (kde text editor). But I'm just not consistent enough to always manage my git properly if its not in the interface reminding me to take care of it. I think its valuable to learn to code in that sort of light environment but when you realize that you want to be better than you are, less unpredictable, find errors sooner, more organized, because you just naturally aren't.... its worth it to just open every project in the ide.

earnest wing
#

Crossposting from #internals-and-peps because I found a very cursed solution to a very cursed problem:

#

I notice that when a descriptor __get__ is called on the class, it's passed None, cls as arguments, whereas with instances it's passed instance, cls.
Now, suppose the descriptor is defined on NoneType. "Would there be any way to distinguish between the two kinds of access?" <- is the question I asked

#

And the solution is to simply patch both NoneType and type

#

class Descriptor:
    def __get__(self, obj, type):
        print("get called", obj, type)
    # ONLY works with a data descriptor
    def __set__(self, obj, value):
        raise AttributeError

import forbiddenfruit
forbiddenfruit.curse(type(None), "test", Descriptor())
forbiddenfruit.curse(type, "test", Descriptor())
    
type(None).test
None.test
get called <class 'NoneType'> <class 'type'>
get called None <class 'NoneType'>

without the type patch, both calls would print None <class 'NoneType'>. (you also get the same bad result if Descriptor isn't a data descriptor, i.e. doesn't define __set__)

rugged sparrow
# quartz wave it's based on chilaxan's `load_addr` function

!e ```py
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]

load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'l', 'd'))()
print(load_addr(id(1)))

night quarryBOT
#

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

1
rugged sparrow
#

it isnt quite as clever as the one that used the range iterator tho ๐Ÿ˜ฆ

echo crown
#

I never want to come back here again

vague cairn
quartz wave
rugged sparrow
#

what?

#

id should return an int

#

@quartz wave what is the return value of id on your system?

quartz wave
rugged sparrow
quartz wave
#

do remember long is only 4 bytes on windows

rugged sparrow
night quarryBOT
#

Objects/memoryobject.c line 1127

case 'l': case 'L': size = sizeof(long); break;```
quartz wave
#

that's exactly also the reason why the range hack won't work on windows

rugged sparrow
#

yea i know that

#

!e ```py
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]

load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'q', 'd'))()
print(load_addr(id(1)))``` hopefully this one works

night quarryBOT
#

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

1
rugged sparrow
#

finally

quartz wave
#

i'm thinking there should probably be a bug report about changing all internal use of long to Py_ssize_t and unsigned long to size_t

#

but that would probably be backwards-incompatible or something

rugged sparrow
#

probably

jovial monolith
#

!e

import forbiddenfruit

class ApproxObject:
    def __init__(self, number, range):
        assert (isinstance(number, int) and isinstance(range, int))
        self.lower_bound = number - abs(range)
        self.upper_bound = number + abs(range)
    def __str__(self):
        return f"Approx [{self.lower_bound}, {self.upper_bound}]"
    def __repr__(self):
        return self.__str__()
    def __eq__(self, other):
        assert isinstance(other, int)
        return other >= self.lower_bound and other <= self.upper_bound

class ApproxObjectCreator:
    def __init__(self, number, range):
        self.number = number
        self.range = range
    def __invert__(self):
        return ApproxObject(self.number, self.range)

forbiddenfruit.curse(int, "__matmul__", lambda self, range: ApproxObjectCreator(self, range))

print(-5 == ~(5 @ 10))
night quarryBOT
#

@jovial monolith :white_check_mark: Your eval job has completed with return code 0.

True
jovial monolith
#

lol

restive void
#

-5 == ~5(+-10) would look better, IMHO

#

And should be doable

jovial monolith
#

!e

import forbiddenfruit
forbiddenfruit.curse(int, "__call__", lambda self, other: print(self * other))
print((5)(123))```
night quarryBOT
#

@jovial monolith :x: Your eval job has completed with return code 1.

001 | <string>:3: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 |   File "/snekbox/user_base/lib/python3.10/site-packages/forbiddenfruit/__init__.py", line 425, in curse
005 |     _curse_special(klass, attr, value)
006 |   File "/snekbox/user_base/lib/python3.10/site-packages/forbiddenfruit/__init__.py", line 332, in _curse_special
007 |     tp_as_name, impl_method = override_dict[attr]
008 | KeyError: '__call__'
jovial monolith
#

cant call it tho

earnest wing
#

!e ```py
from fishhook import hook
@hook(int)
def call(self, other):
return self * other

print((5)(123))

night quarryBOT
#

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

001 | <string>:6: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | 615
earnest wing
#

you can, forbiddenfruit just doesn't let you

floral meteor
#

why isn't it?

#

going into python as a mathematician, I always tried to do that with ints.
for example, before actually learning python I was very disappointed when y = 4x^2 + 2(x+3) didn't work

earnest wing
#

Try Julia

#

The reason it doesn't work of course is parsing ambiguities

restive void
quartz wave
#

only in my modified cpython

earnest wing
restive void
earnest wing
#

Ah I see

restive void
#

!e

import dis
dis.dis("+-10")
night quarryBOT
#

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

001 |   1           0 LOAD_CONST               0 (-10)
002 |               2 RETURN_VALUE
earnest wing
#

Yeah then some trickery in call is necessary

restive void
#

right, that could work

echo crown
#

leviathan? subnautica fans shivering rn

quartz wave
terse oriole
#

!e

(lambda outside,inside,outer,inner:(lambda shell:[print(shell),(lambda buffer:print("\n".join([f"{outside}{inside*inner:^{buffer}}{outside}"for _ in " "*inner])))(outer-2),print(shell[::-1])])(outside*outer+("\n" if outer-inner-2 else "")+"\n".join(outside+" "*(outer-2)+outside for _ in range((outer-inner)//2-1))))("#","~",7,3)
night quarryBOT
#

@terse oriole :white_check_mark: Your eval job has completed with return code 0.

001 | #######
002 | #     #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | #     #
007 | #######
terse oriole
#

any idea of how to shorten this without changing variable names?

quartz wave
#
..."\n" if...
       ^ also here
...2 else ""...
    ^    ^
also these places
terse oriole
#

oh wait what that works?

#

I thought you can only do that if its a bracket

quartz wave
#

but the number-before-identifier thingy is deprecated in 3.11

terse oriole
#

I see

lusty sinew
#

does anyone have a one-liner for installing packages with pip?

quartz wave
terse oriole
#

!e
shortened it to this

(lambda o,i,b,a,p:(lambda s:[p(s),(lambda u:p("\n".join([f"{o}{i*a:^{u}}{o}"for _ in" "*a])))(b-2),p(s[::-1])])(o*b+("\n"if b-a-2else"")+"\n".join(o+" "*(b-2)+o for _ in" "*((b-a)//2-1))))("#","~",7,3,print)
night quarryBOT
#

@terse oriole :white_check_mark: Your eval job has completed with return code 0.

001 | #######
002 | #     #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | #     #
007 | #######
terse oriole
#

not sure what else I can do

sick hound
#

!e
(lambda o,i,b,a,p:(lambda s:[p(s),(lambda u:p("\n".join([f"{o}{ia:^{u}}{o}"for _ in" "a])))(b-2),p(s[::-1])])(ob+("\n"if b-a-2else"")+"\n".join(o+" "(b-2)+o for _ in" "*((b-a)//2-1))))("#","~",7,3,print)

night quarryBOT
#

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

001 | #######
002 | #     #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | #     #
007 | #######
sick hound
#

cool

floral meteor
#

noice

static dirge
frigid wharf
sick hound
#

life is a conundrum of esoterica

#

Change everything to esoterica

#

esoterica esoterica esoterica esoterica esoterica esoterica

#

someone should make a language literally made of the word esoterica

quartz wave
#

it's literally made of the word "chicken"

rapid sparrow
#

I wanted to show off my simple module traversing code

#
import bs4
from inspect import getmembers, ismodule
from pprint import pprint

def find_members(module):
  results = {module.__name__: module}
  for k, m in getmembers(module, ismodule):
    if m.__name__.startswith(module.__name__):
     results.update(find_members(m))
  return results

pprint(find_members(bs4))
#

outputs:

{'bs4': <module 'bs4' from '/usr/local/lib/python3.9/dist-packages/bs4/__init__.py'>,
 'bs4.builder': <module 'bs4.builder' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/__init__.py'>,
 'bs4.builder._html5lib': <module 'bs4.builder._html5lib' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_html5lib.py'>,
 'bs4.builder._htmlparser': <module 'bs4.builder._htmlparser' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_htmlparser.py'>,
 'bs4.builder._lxml': <module 'bs4.builder._lxml' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_lxml.py'>,
 'bs4.dammit': <module 'bs4.dammit' from '/usr/local/lib/python3.9/dist-packages/bs4/dammit.py'>,
 'bs4.element': <module 'bs4.element' from '/usr/local/lib/python3.9/dist-packages/bs4/element.py'>,
 'bs4.formatter': <module 'bs4.formatter' from '/usr/local/lib/python3.9/dist-packages/bs4/formatter.py'>}```
#

that I had just written somebody in a help channel

#

since the person left ๐Ÿ˜„

#

the one issue is this code does not eagerly load submodules

#

but I've gotten into trouble doing so

#

so this is probably a start

#

my workaround is to catch SystemExit ๐Ÿ˜‚

#

so as to prevent annoying exits of the program while loading child modules ..

#

and skipping some things

#
>>> print(importAll(lsmod(bs4)))
bs4: [OK]
bs4.builder: [OK]
bs4.builder._html5lib: [OK]
bs4.builder._htmlparser: [OK]
bs4.builder._lxml: [OK]
bs4.dammit: [OK]
bs4.diagnose: [OK]
bs4.element: [OK]
bs4.formatter: [OK]
bs4.testing: Skipping
bs4.tests: Skipping
bs4.tests.test_builder_registry: Skipping
bs4.tests.test_docs: Skipping
bs4.tests.test_html5lib: Skipping
bs4.tests.test_htmlparser: Skipping
bs4.tests.test_lxml: Skipping
bs4.tests.test_soup: Skipping
bs4.tests.test_tree: Skipping
{'bs4': <module 'bs4' from '/usr/local/lib/python3.9/dist-packages/bs4/__init__.py'>, 'bs4.builder': <module 'bs4.builder' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/__init__.py'>, 'bs4.builder._html5lib': <module 'bs4.builder._html5lib' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_html5lib.py'>, 'bs4.builder._htmlparser': <module 'bs4.builder._htmlparser' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_htmlparser.py'>, 'bs4.builder._lxml': <module 'bs4.builder._lxml' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_lxml.py'>, 'bs4.dammit': <module 'bs4.dammit' from '/usr/local/lib/python3.9/dist-packages/bs4/dammit.py'>, 'bs4.diagnose': <module 'bs4.diagnose' from '/usr/local/lib/python3.9/dist-packages/bs4/diagnose.py'>, 'bs4.element': <module 'bs4.element' from '/usr/local/lib/python3.9/dist-packages/bs4/element.py'>, 'bs4.formatter': <module 'bs4.formatter' from '/usr/local/lib/python3.9/dist-packages/bs4/formatter.py'>}```
#

yes it's camel case ( I named it before I was enlightened)

sick hound
severe canyon
#

If you want a chicken implementation, I did one here :)

Can probably get shorter

split salmon
#

YES

scarlet nymph
#

anyboady in vr career and pursuing it

modern sage
wild saddle
#

I came up with this crazy one liner which will use a monte carlo method to approximate pi

print(4*len([point for point in [(__import__('random', globals(), locals(), [], 0).random() * 2 -1, __import__('random', globals(), locals(), [], 0).random() * 2 - 1) for x in range(100000)] if point[0] ** 2 + point[1] ** 2 < 1])/100000)
#

!e

print(4*len([point for point in [(__import__('random', globals(), locals(), [], 0).random() * 2 -1, __import__('random', globals(), locals(), [], 0).random() * 2 - 1) for x in range(100000)] if point[0] ** 2 + point[1] ** 2 < 1])/100000)
night quarryBOT
#

@wild saddle :white_check_mark: Your eval job has completed with return code 0.

3.13976
quartz wave
#

!e i came up with this crazier one liner which will print pi to the max amount of digits that python can handle with the float class ```py
print(import('math').pi)

night quarryBOT
#

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

3.141592653589793
wild saddle
#

the one liner I wrote could theoretically calculate pi to infinite digits

quartz wave
#

hmm let's see

wild saddle
#

even the more efficent methods of calculating pi with riemann functions and such are pretty intense and require a lot of iterations to reach accuracy

quartz wave
#

also it only calculates pi to 2 digits after the decimal point

#

approximately 2 digits and exactly correct only for 1 digit after the decimal point

wild saddle
#

Im aware that that my one liner sucks at calculating pi

stoic rose
#

hey guys one line _with statement?

wild saddle
#

but the idea that you could actually calculate pi in a one liner is crazy

quartz wave
#

some other one liners can calculate pi to infinite digits

wild saddle
#

this one can

#

with infinite computing resources

quartz wave
#

tested with the decimal.Decimal() class

wild saddle
quartz wave
wild saddle
#

when running

print(4*len([point for point in [(__import__('random').random() * 2 -1, __import__('random').random() * 2 - 1) for x in range(10000000)] if point[0] ** 2 + point[1] ** 2 < 1])/10000000)

on my own computer I got the result 3.1419104

#

so by adjusting the amount of times you iterate through the monte carlo method you can get infintely precise (which I have so far not been able to see python obstruct)

quartz wave
#

it's a little slow

wild saddle
#

obviously

quartz wave
wild saddle
#

oh yeah for sure

#

the method I used here is almost certainly the least efficent way of calculating pi, which is why I thought it would be fun to implement as a one liner

quartz wave
#

but you didn't need to add extra arguments to __import__

wild saddle
#

!e

print(4*len([point for point in [(__import__('random').random() * 2 -1, __import__('random').random() * 2 - 1) for x in range(10000)] if point[0] ** 2 + point[1] ** 2 < 1])/10000)
night quarryBOT
#

@wild saddle :white_check_mark: Your eval job has completed with return code 0.

3.1252
wild saddle
#

true thanks

quartz wave
sly root
#

it's slightly shorter

quartz wave
sly root
#

also

SyntaxError: assignment expression cannot be used in a comprehension iterable expression```
#

so (r:=__import__('random').random) should be moved out of print

#
r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)```
#
>>> len("""r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)""")
138
>>> len("""print(4*len([point for point in[((r:=__import__('random').random)()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)""")
139
>>>```
quartz wave
#

!e ```py
r=import('random').random;print(4*len((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)/105)

night quarryBOT
#

@quartz wave :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 <listcomp>
004 | NameError: name 'p' is not defined
sly root
#

!e py r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

3.14264
sly root
#

!e py r=__import__('random').random;print(4*len([p for(p)in[(r()*2-1,r()*2-1)for x in range(10**5)]if p[0]**2+p[1]**2<1])/10**5)

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

3.14468
quartz wave
#

!e ```py
r=import('random').random;print(4*len((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)/105)

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: object of type 'generator' has no len()
quartz wave
#

!e ```py
r=import('random').random;print(4len([((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)])/105)

night quarryBOT
#

@quartz wave :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 <genexpr>
004 | NameError: name 'p' is not defined
sly root
#

assign p at p[0]

#

(p:=...)[0]

#

it should work

quartz wave
#

!e ```py
r=import('random').random;print(4*len([p for _ in range(10**5)if (p:=(r()*2-1,r()*2-1))[0]**2+p[1]2<1])/105)

night quarryBOT
#

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

3.14644
quartz wave
#

!e ```py
r=import('random').random;print(len([p for _ in range(10**5)if (p:=(r()*2-1,r()*2-1))[0]**2+p[1]**2<1])/25e3)

night quarryBOT
#

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

3.13552
quartz wave
#

probably shortest version we have yet

#

!e ```py
r=import('random').random;print(sum((r()*2-1)**2+(r()*2-1)2<1for _ in range(105))/25e3)

night quarryBOT
#

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

3.13556
quartz wave
#

we've done it

#

it's the shortest it has ever been

quartz wave
sly root
#

with moving import to header section

#
>>> len("print(sum((r()*2-1)**2+(r()*2-1)**2<1for _ in range(10**5))/25e3)")
65
>>>```
quartz wave
#

95 from 237

sly root
#

somehow ive got OverflowError: (34, 'Math result not representable')

#

lmao

earnest wing
#

!e ```py
from random import random as r

just 1 quadrant

print(sum(r()**2+r()2<1for()in[()]*105)/25e3)

night quarryBOT
#

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

3.132
severe canyon
#

!e

print(22/7)
night quarryBOT
#

@severe canyon :white_check_mark: Your eval job has completed with return code 0.

3.142857142857143
severe canyon
#

did i win?

#

:)

fleet bridge
#

!e

print(((-1)**(t:=1e-9)).imag/t)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

3.141592653589793
fleet bridge
#

Did i win?

#

!e

ฯ€ = ((-1)**(t:=1e-9)).imag/t
import math
assert ฯ€ == math.pi
print(ฯ€)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

3.141592653589793
fleet bridge
#

!e

print(((-1)**1e-9).imag*1e9)
print(((-1)**(t:=1e-9)).imag/t)โ€Š
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | 3.141592653589793
002 | 3.141592653589793
sleek sphinx
#

cause of e to the i pi? (euler's formula or something)

turbid dragon
#

!e ```py
print(((-1)**1e-100).imag*1e100)

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

3.141592653589793
turbid dragon
#

rip

knotty delta
knotty delta
#

and 1e-1 is 0.1

#

I hope I'm not wrong

arctic elm
#

it's scientific notation

#

1.23e4 = 1.23 * 10โด

knotty delta
#

sometimes I know what it is, but I forgor the name

#

๐Ÿ˜”

long hamlet
knotty delta
#

evil ram ๐Ÿ˜ 

coral sluice
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

coral sluice
#
import numpy as np
import matplotlib.pyplot as plt

grid = np.zeros(100*100).reshape(100, 100)

plt.imshow(grid)

plt.show()

Does anyone have issues running this code ?
Whenever i run it everything seems normal until i put my mouse on the pyplot something like this happens

sleek sphinx
coral sluice
#

and it starts glitching out non stop

sleek sphinx
#

i forgot what

coral sluice
#

any issues with the code or matplotlib is just broken or smth

coral sluice
#

alright, my bad

sleek sphinx
#

thanks

split salmon
#
print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โ€Š

sus :)

quartz wave
#

the first letter is N

#

the last letter is p

split salmon
#

Yes, so?

knotty delta
#

could've been better if you didn't add that "so?", like if you don't care why post here

jovial monolith
#

!e

print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โ€Šโ€Š
night quarryBOT
#

@jovial monolith :white_check_mark: Your eval job has completed with return code 0.

Never Gonna Give You Up
jovial monolith
#

ouch

wild sable
#

how to write this code in one line

proud bone
# wild sable
inp = input();print(f"Original list: {list(map(int, inp.split()))}\nModified list: {list(filter(lambda i2: int(i2) % 2, list(map(int, inp.split()))))}")
``` got this rn but can be better
quartz wave
# wild sable
print(f"Original list: {eval('(u_list:=[*map(int,input().split())])',globals(),globals())}\nModified list: {eval('(m_list:=[x for x in u_list if x&1])',globals(),globals())}")
quartz wave
#

it's now just on one line with only one expression

proud bone
wild sable
#

ok thanks

#

!close

#

no need to close?

knotty delta
#

:)

wild sable
#

got it

wheat river
#

!e

from math import sqrt
ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit+length+int(sq))}\n' if i != limit  else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(9, 5))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 |   1  |  2  |  3  
002 | -----------------
003 |   4  |  5  |  6  
004 | -----------------
005 |   7  |  8  |  9  
wheat river
#

!e

from math import sqrt

ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit+length+int(sq))}\n' if i != limit  else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | ------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | ------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | ------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | ------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | --------------------------------------------------------------------------------
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/uvufipenib.txt?noredirect

wheat river
#

:(

#

!e

ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit*2-length*2)}\n' if i != limit  else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))```
night quarryBOT
#

@wheat river :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | NameError: name 'sqrt' is not defined
wheat river
#

-_-

#

!e

from math import sqrt

ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit*2-length*2)}\n' if i != limit  else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/bujudavitu.txt?noredirect

primal scroll
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

night quarryBOT
#

Hey @shut smelt!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

sly root
#

it works but idk what is expected from it

faint ether
#

SPOILER: this file contains code that will scare you for life
its so unreadable I don't think you'd ever want to touch this or even KEEP this on your computer

night quarryBOT
faint ether
#

oh

finite blaze
#

I might be missing something, but whats esoteric in your code?

earnest wing
#

it's certainly wide :>

split salmon
sly root
#

!e py exec(__import__("types").CodeType( 0,0,0,0,4,64, bytes([100,0, 100,1, 132,0, 90,0, 101,1, 101,0, 100,2, 100,3, 132,0, 131,1, 131,1, 1,0, 100,4, 83,0,]), ('a','<lambda>',None,),('a','print'), (),'','<module>', 1, bytes([8,2,]), (),()))

night quarryBOT
#

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

[No output]
sly root
#

challenge for everyone in this channel, guess why its giving sigsegv if everyting is written correctly๐Ÿค”

earnest wing
#

!e py __import__("dis").dis(__import__("types").CodeType( 0,0,0,0,4,64, bytes([100,0, 100,1, 132,0, 90,0, 101,1, 101,0, 100,2, 100,3, 132,0, 131,1, 131,1, 1,0, 100,4, 83,0,]), ('a','<lambda>',None,),('a','print'), (),'','<module>', 1, bytes([8,2,]), (),()))

night quarryBOT
#

@earnest wing :x: Your eval job has completed with return code 1.

001 |   3           0 LOAD_CONST               0 ('a')
002 |               2 LOAD_CONST               1 ('<lambda>')
003 |               4 MAKE_FUNCTION            0
004 |               6 STORE_NAME               0 (a)
005 |               8 LOAD_NAME                1 (print)
006 |              10 LOAD_NAME                0 (a)
007 |              12 LOAD_CONST               2 (None)
008 | Traceback (most recent call last):
009 |   File "<string>", line 1, in <module>
010 |   File "/usr/local/lib/python3.10/dis.py", line 79, in dis
011 |     _disassemble_recursive(x, file=file, depth=depth)
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/yokuhizedi.txt?noredirect

earnest wing
#

!e print(import("dis").opmap)

night quarryBOT
#

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

{'POP_TOP': 1, 'ROT_TWO': 2, 'ROT_THREE': 3, 'DUP_TOP': 4, 'DUP_TOP_TWO': 5, 'ROT_FOUR': 6, 'NOP': 9, 'UNARY_POSITIVE': 10, 'UNARY_NEGATIVE': 11, 'UNARY_NOT': 12, 'UNARY_INVERT': 15, 'BINARY_MATRIX_MULTIPLY': 16, 'INPLACE_MATRIX_MULTIPLY': 17, 'BINARY_POWER': 19, 'BINARY_MULTIPLY': 20, 'BINARY_MODULO': 22, 'BINARY_ADD': 23, 'BINARY_SUBTRACT': 24, 'BINARY_SUBSCR': 25, 'BINARY_FLOOR_DIVIDE': 26, 'BINARY_TRUE_DIVIDE': 27, 'INPLACE_FLOOR_DIVIDE': 28, 'INPLACE_TRUE_DIVIDE': 29, 'GET_LEN': 30, 'MATCH_MAPPING': 31, 'MATCH_SEQUENCE': 32, 'MATCH_KEYS': 33, 'COPY_DICT_WITHOUT_KEYS': 34, 'WITH_EXCEPT_START': 49, 'GET_AITER': 50, 'GET_ANEXT': 51, 'BEFORE_ASYNC_WITH': 52, 'END_ASYNC_FOR': 54, 'INPLACE_ADD': 55, 'INPLACE_SUBTRACT': 56, 'INPLACE_MULTIPLY': 57, 'INPLACE_MODULO': 59, 'STORE_SUBSCR': 60, 'DELETE_SUBSCR': 61, 'BINARY_LSHIFT': 62, 'BINARY_RSHIFT': 63, 'BINARY_AND': 64, 'BINARY_XOR': 65, 'BINARY_OR': 66, 'INPLACE_POWER': 67, 'GET_ITER': 68, 'GET_YIELD_FROM_ITER': 69, 'PRINT_EXPR': 70, 'LOA
... (truncated - too long)

Full output: https://paste.pythondiscord.com/popisixewi.txt?noredirect

earnest wing
#

that 100, 3 is reading out of bounds from the co_consts tuple

#

because bounds checking is slow

sly root
#

hmm

earnest wing
#

oh is this like a question or a challenge

quartz wave
night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/eyabiwovoj.txt?noredirect

sick hound
#

The syntax... the dirty unorganized code

#

I think I am going to be sick

quartz wave
sick hound
#

I need to bring some holy water and a cross for this chat

#

Sweet baby kitten I need a whole water tower of holy water

quartz wave
#

!e ```py
print((lambda l,n:[s:=l**.5,''.join([f'''{i:^{n}}{"|"(i%s>0)}{("-"(l2-n2)).join("""

""")*(i%s<1)}'''if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))

night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/egeguvolud.txt?noredirect

quartz wave
#

!e ```py
print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}'+f'''{"|"(i%s>0)}{("-"(l2-n2)).join("""

""")(i%s<1)}'''(i!=l)for i in range(1,l+1)])][1])(64,12))

night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/hayeyizaho.txt?noredirect

quartz wave
sick hound
#

nsfw python moment

sly root
night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/fowesiqaza.txt?noredirect

sly root
#

was 149 chars
now is 147 chars

quartz wave
sly root
#

ah

#

133

#

!e py print((lambda l,n:''.join([((f'{i:^{n}}',f'{i:^{n}}\n{"-"*(l*2-n*2)}\n')[i!=l],f'{i:^{n}}|')[i%l**.5>0]for i in range(1,l+1)]))(64,12))

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/azuwipasaj.txt?noredirect

quartz wave
sly root
#

i think everything that is posted in this channel must be automatically golfed to 1 byte

quartz wave
#

!e more hardcoding ```py
print(*[(f'{i:^{12}}\n{"-"*104}\n',f'{i:^{12}}|')[i%8>0]for i in range(1,64)],f'{64:^{12}}',sep='')

night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/asefimalam.txt?noredirect

quartz wave
#

!e complete remodel of code ```py
print(*['|'.join(f'{x:^{12}}'for x in range(y-7,y+1))for y in range(8,65,8)],sep=f'\n{"-"*104}\n')

night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/putirezoni.txt?noredirect

sick hound
#

!e

print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}|'if i%s else f'{i:^{n}}\n{"-"*(l*2-n*2)}\n'if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
#

!e

print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}|'if i%s else f'{i:^{n}}\n{"-"*(l*2-n*2)}\n'if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
night quarryBOT
#

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

001 |      1      |     2      |     3      |     4      |     5      |     6      |     7      |     8      
002 | --------------------------------------------------------------------------------------------------------
003 |      9      |     10     |     11     |     12     |     13     |     14     |     15     |     16     
004 | --------------------------------------------------------------------------------------------------------
005 |      17     |     18     |     19     |     20     |     21     |     22     |     23     |     24     
006 | --------------------------------------------------------------------------------------------------------
007 |      25     |     26     |     27     |     28     |     29     |     30     |     31     |     32     
008 | --------------------------------------------------------------------------------------------------------
009 |      33     |     34     |     35     |     36     |     37     |     38     |     39     |     40     
010 | 
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/limikafuge.txt?noredirect

wheat river
#

!e

from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter

@contextmanager
def timer(name):
    start = perf_counter()
    yield
    end = perf_counter()
    print(f'{name:<50} | {end - start} s')

def collatz_conj(num):
    return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]


with timer('10e1000'):
    print(collatz_conj(int(10e100)))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | [49999999999999998852475663262266831422342135996207500306499798736599672609039495565163064724075577344, 24999999999999999426237831631133415711171067998103750153249899368299836304519747782581532362037788672, 12499999999999999713118915815566707855585533999051875076624949684149918152259873891290766181018894336, 6249999999999999856559457907783353927792766999525937538312474842074959076129936945645383090509447168, 3124999999999999928279728953891676963896383499762968769156237421037479538064968472822691545254723584, 1562499999999999964139864476945838481948191749881484384578118710518739769032484236411345772627361792, 781249999999999982069932238472919240974095874940742192289059355259369884516242118205672886313680896, 390624999999999991034966119236459620487047937470371096144529677629684942258121059102836443156840448, 195312499999999995517483059618229810243523968735185548072264838814842471129060529551418221578420224, 976562499999999977587415298091149051217619843675927740361324194074212355645
... (truncated - too long)

Full output: too long to upload

wheat river
#

:(

#

!e

from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter

@contextmanager
def timer(name):
    start = perf_counter()
    yield
    end = perf_counter()
    print(f'{name:<50} | {end - start} s')

def collatz_conj(num):
    return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]


with timer('10e1000'):
    (collatz_conj(int(10e100)))
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

10e1000                                            | 0.0004028184339404106 s
wheat river
#

tf

#

!e

from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter

@contextmanager
def timer(name):
    start = perf_counter()
    yield
    end = perf_counter()
    print(f'{name:<50} | {end - start} s')

def collatz_conj(num):
    return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]


with timer('10e1000'):
    (collatz_conj(int(10e1000)))
night quarryBOT
#

@wheat river :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 17, in <module>
003 | OverflowError: cannot convert float infinity to integer
wheat river
#

!e

from itertools import count, takewhile
from contextlib import contextmanager
from time import time
from pprint import pprint

@contextmanager
def timer(name):
    start = time()
    yield
    end = time()
    print(f'{name:<50} | {end - start} s')

def collatz_conj(num):
    return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]


with timer('10e1000'):
    collatz_conj(10**100)

night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

10e1000                                            | 0.001003265380859375 s
wheat river
#

!e

from itertools import count, takewhile
from contextlib import contextmanager
from time import time
from pprint import pprint

@contextmanager
def timer(name):
    start = time()
    yield
    end = time()
    print(f'{name:<50} | {end - start} s')

def collatz_conj(num):
    return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]


with timer('10^1000'):
    collatz_conj(10**10000)

night quarryBOT
#

@wheat river :warning: Your eval job timed out or ran out of memory.

[No output]
sick hound
#

where can i learn these?

sick hound
#

!e
a = 1

night quarryBOT
#

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

[No output]
sick hound
#

easy

sly root
wheat river
bronze merlin
#

alternative way to do while? i've learn while True already and now i want to learn while x < {num}

wheat river
#

there are another type of loop called for, it iterates over iterable objects likes list, tuple, str

sick hound
#

whats altera of if

wheat river
#

its not really conditional

bronze merlin
#

like uhh

#

i'm doing some project

#

and i can't test it myself

#

because i'm the owner

#

and the bot can't change my name that's the thing

wheat river
bronze merlin
#

aight

split salmon
#

hi

#

if any ppl here become active, ping me plz

#

look

#
import urllib.request;exec(open(urllib.request.urlretrieve('https://raw.githubusercontent.com/AFK-debug-9/test/main/test.py')[0],'r').read())``` (pulls that via internet)
#

!e py import urllib.request;exec(open(urllib.request.urlretrieve('https://raw.githubusercontent.com/AFK-debug-9/test/main/test.py')[0],'r').read())

night quarryBOT
#

@split salmon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/usr/local/lib/python3.10/urllib/request.py", line 1348, in do_open
003 |     h.request(req.get_method(), req.selector, req.data, headers,
004 |   File "/usr/local/lib/python3.10/http/client.py", line 1282, in request
005 |     self._send_request(method, url, body, headers, encode_chunked)
006 |   File "/usr/local/lib/python3.10/http/client.py", line 1328, in _send_request
007 |     self.endheaders(body, encode_chunked=encode_chunked)
008 |   File "/usr/local/lib/python3.10/http/client.py", line 1277, in endheaders
009 |     self._send_output(message_body, encode_chunked=encode_chunked)
010 |   File "/usr/local/lib/python3.10/http/client.py", line 1037, in _send_output
011 |     self.send(msg)
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/voqewimevu.txt?noredirect

split salmon
#

no net :(

rugged sparrow
#

the bot does not have network access by design

bronze merlin
split salmon
split salmon
bronze merlin
#

na i'm bad at those

split salmon
bronze merlin
#

no thx mate

split salmon
sly root
#

!e ```py
import sys,time,itertools,threading
class UnixLoading:
def enter(s):
def __thr(s):
for(_l)in itertools.cycle("|/-\"):
sys.stdout.write(f"{_l} Loading\r")
sys.stdout.flush()
time.sleep(.29)
s.t=threading.Thread(target=__thr,args=(s,),daemon=True)
s._s=int(str(time.clock_gettime_ns(0))[0:13])
s.t.start()
def exit(s,t,v,b):
s.t._delete();s._e=int(str(time.clock_gettime_ns(0))[0:13])
if t is not None:sys.stdout.write(f"โŒ Error after {abs((s._s-s._e)/1000)} seconds.\n\r");sys.stdout.flush()
else:sys.stdout.write(f"โœ… Success. (lasted {abs((s._s-s._e)/1000)} seconds.)\n\r");sys.stdout.flush()

with UnixLoading():
import requests
a = requests.get("https://zeronet.space")
print(b)```

night quarryBOT
#

@sly root :x: Your eval job has completed with return code 1.

001 | | Loading
002 | โŒ Error after 0.002 seconds.
003 | 
004 | Traceback (most recent call last):
005 |   File "<string>", line 18, in <module>
006 | ModuleNotFoundError: No module named 'requests'
sly root
#

ah

#

!e ```py
import sys,time,itertools,threading
class UnixLoading:
def enter(s):
def __thr(s):
for(_l)in itertools.cycle("|/-\"):
sys.stdout.write(f"{_l} Loading\r")
sys.stdout.flush()
time.sleep(.29)
s.t=threading.Thread(target=__thr,args=(s,),daemon=True)
s._s=int(str(time.clock_gettime_ns(0))[0:13])
s.t.start()
def exit(s,t,v,b):
s.t._delete();s._e=int(str(time.clock_gettime_ns(0))[0:13])
if t is not None:sys.stdout.write(f"โŒ Error after {abs((s._s-s._e)/1000)} seconds.\n\r");sys.stdout.flush()
else:sys.stdout.write(f"โœ… Success. (lasted {abs((s._s-s._e)/1000)} seconds.)\n\r");sys.stdout.flush()

with UnixLoading():
print("hello world")```

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

001 | | Loading
002 | hello world
003 | โœ… Success. (lasted 0.001 seconds.)
uncut bolt
#

!e

def sqrt(num):
    num=abs(num)
    guessfrom=0
    guessto=1

    while guessto*guessto < num:
        guessfrom=guessto
        guessto=guessto*2

    margin=0.000000000001*num
    guess=(guessfrom+guessto)/2

    while not abs(num-(guess*guess)) <= margin:
        if num-(guess*guess) > margin:
            guessfrom+=(guessto-guessfrom)/2
        else:
            guessto-=(guessto-guessfrom)/2
        guess=(guessfrom+guessto)/2

    return guess
night quarryBOT
#

@uncut bolt :warning: Your eval job has completed with return code 0.

[No output]
uncut bolt
#

!e

def sqrt(num):
    num=abs(num)
    guessfrom=0
    guessto=1

    while guessto*guessto < num:
        guessfrom=guessto
        guessto=guessto*2

    margin=0.000000000001*num
    guess=(guessfrom+guessto)/2

    while not abs(num-(guess*guess)) <= margin:
        if num-(guess*guess) > margin:
            guessfrom+=(guessto-guessfrom)/2
        else:
            guessto-=(guessto-guessfrom)/2
        guess=(guessfrom+guessto)/2

    return guess

print(sqrt(25))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

5.0
uncut bolt
#

working on lambdaified version

#

!e

sqrt=lambda num: (
    (lambda num,margin,guessL,i: (
        len([(lambda num,margin,guessL,i: 
            None if abs(num-(guessL[-1]*guessL[-1])) <= margin else (
                (
                    guessL.__setitem__(0,guessL[0]+(guessL[1]-guessL[0])/2) 
                        if num-(guessL[-1]*guessL[-1]) > margin
                    else guessL.__setitem__(1,guessL[1]-(guessL[1]-guessL[0])/2) 
                ) or guessL.__setitem__(-1,(guessL[1]+guessL[0])/2)
                or print(guessL)
            ) or i.append(None)
        ) (num,margin,guessL,i) for _ in zip(i)])*0 + guessL[-1]
    )) (
        abs(num),
        0.000000000001*num,
        (lambda num,guessL,i: ([
            (lambda num,guessL,i:(
                (guessL[0]*guessL[1] < num) and (
                    i.append(None) or 
                    guessL.__setitem__(0,guessL[1]) or 
                    guessL.__setitem__(1,guessL[1]*2) or 
                    guessL.__setitem__(2,(guessL[0]+guessL[1])/2)
                )
            )) (num,guessL,i) for _ in zip(i)
        ]*0 + guessL) ) (abs(num),[0,1,.5],[None]),
        [None]
    )
)

print(sqrt(25))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

001 | [4, 6.0, 5.0]
002 | 5.0
uncut bolt
#

!e

sqrt=lambda n: (
    (lambda n,m,g,i: 
        len([(lambda n,m,g,i: 
            0 if abs(n-(g[-1]*g[-1])) <= m else 
                
                    g.__setitem__(0,g[0]+(g[1]-g[0])/2) 
                        if n-(g[-1]*g[-1]) > m
                    else g.__setitem__(1,g[1]-(g[1]-g[0])/2) 
                 or g.__setitem__(-1,(g[1]+g[0])/2)
             or i.append(0)
        ) (n,m,g,i) for _ in zip(i)])*0 + g[-1]
    ) (
        abs(n),
        1e-12*n,
        (lambda n,g,i: [
            (lambda n,g,i:
                g[0]*g[1] < n and (
                    i.append(0) or 
                    g.__setitem__(0,g[1]) or 
                    g.__setitem__(1,g[1]*2) or 
                    g.__setitem__(2,(g[0]+g[1])/2)
                )
            ) (n,g,i) for _ in zip(i)
        ]*0 + g ) (abs(n),[0,1,.5],[0]),
        [0]
    )
)

print(sqrt(25))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

5.0
uncut bolt
#

minified

#

!e

sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>m else g.__setitem__(1,g[1]-(g[1]-g[0])/2)or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),1e-12*n,(lambda n,g,i:[(lambda n,g,i:g[0]*g[1]<n and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))

print(sqrt(5))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

2.125
uncut bolt
#

one-linified

#

i think im slowly going insane

uncut bolt
#

!e

sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),0.000000000001*n,(lambda n,g,i:[(lambda n,g,i:(g[1]*g[1]<n)and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))

print(sqrt(3))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

1.7320508075681573
uncut bolt
#

fixed edge case where 3 would be an infinite loop

uncut bolt
#

!e

sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:(g[1]*g[1]<n)and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))

print(sqrt(1))
night quarryBOT
#

@uncut bolt :white_check_mark: Your eval job has completed with return code 0.

0.9999999999995453
uncut bolt
#

Shortened the 0.000000000001

quartz wave
#

!e ```py
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.setitem(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.setitem(1,g[1]-(g[1]-g[0])/2))or g.setitem(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))

print(sqrt(1))
print(sqrt(3))

night quarryBOT
#

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

001 | 0.9999999999995453
002 | 1.7320508075681573
quartz wave
#

i like the *0+g tricks that you do

uncut bolt
#

thanks

quartz wave
#

only for 3.8+ though

#

!e ```py
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))

print(sqrt(1))
print(sqrt(3))

night quarryBOT
#

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

001 | 0.9999999999995453
002 | 1.7320508075681573
quartz wave
#

shortened even more by replacing py 0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0) with ```py
abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0))

#

!e shortened ten characters ```py
sqrt=lambda n:(lambda n,m,g,i:len([(lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i)for _ in zip(i)])*0+g[-1])(a:=abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(a,[0,1,.5],[0]),[0])

print(sqrt(1))
print(sqrt(3))

night quarryBOT
#

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

001 | 0.9999999999995453
002 | 1.7320508075681573
uncut bolt
#

๐Ÿคฏ epic

sly root
#

!e ```py
sqrt=lambda n:(lambda n,m,g,i:len([map((lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i),zip(i))])*0+g[-1])(a:=abs(n),n/1e12,(lambda n,g,i:[map((lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i),zip(i))]*0+g)(a,[0,1,.5],[0]),[0])

print(sqrt(1))
print(sqrt(3))```

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

001 | 0.75
002 | 1.75
sly root
#

but ye

prisma coral
#

!e Different method, but still kinda cool:

sqrt=lambda n:(f:=lambda x:(x+n/x)/2)(f(f(f(n/2))))
print(f"{sqrt(9) = }")
print(f"{sqrt(3) = }")
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

001 | sqrt(9) = 3.0000000000393214
002 | sqrt(3) = 1.7320508075688772
runic mirage
#

!e

collatz=lambda n:(i:=[n],[*iter(lambda:(y:=i[-1],i.append((y//2,3*y+1)[y%2]),i[-1])[-1],1)],i)[-1]

print(collatz(7))```
night quarryBOT
#

@runic mirage :white_check_mark: Your eval job has completed with return code 0.

[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
shell seal
#

Lol wtf this stuff is definitely esoteric

#

Hope job interviews don't ask me how to do this stuff

earnest wing
#

I did a little more work on my thing

#

The API ended up surprisingly thorough

#
@literal(int, str)
def foo(self): ...

@literals(int, str)
class Foos:
  def foo(self): ...
  @rename("bar")
  def bartholomew(self): ...

with literally(int, str, name="foo", fn=...):
  ...

Three different ways to hook

#

inspired in some ways by the forbiddenfruit and fishhook APIs

earnest wing
#

Oh, I just tweaked the context manager so the API is even smoother

prisma coral
terse oriole
#

I've tried making something like this but my brain is too small

amber ravine
# terse oriole Woah how does this work?

it's a context manager, it can overwrite functions on modules or even stuff like int and strings, and save the old functionality to later restore the original behavior

#

it's a neat idea but if you ever saw it in the wild you'd want to off yourself

earnest wing
#

(plus this allows multiple targets & literals atm, so literally(int, float, minutes=..., seconds=...) is useable)

prisma coral
silver olive
earnest wing
#

Collection types supported now

#

I guess that example would be even simpler with with literally(set, f=frozenset):

quartz wave
earnest wing
#

It also detects when it's used in a "non-literal" context and fails

#
x = {1, 2}
x.f # raises
#

(you can disable this with strict=False but why would you!!! bytecode analysis is so cool and not at all fragile)

quartz wave
earnest wing
#

only load_const, build_list, build_map and build_set are allowed to be the last executed op when strict=True

earnest wing
#

when's that called

quartz wave
# earnest wing when's that called
>>> dis("assert {1,2,3,4}.f == frozenset({1, 2, 3, 4})")
  1           0 BUILD_SET                0
              2 LOAD_CONST               0 (frozenset({1, 2, 3, 4}))
              4 SET_UPDATE               1      <<<<<<<<<<<<<<<<<<<<<<<<
              6 LOAD_ATTR                0 (f)
              8 LOAD_NAME                1 (frozenset)
             10 BUILD_SET                0
             12 LOAD_CONST               0 (frozenset({1, 2, 3, 4}))
             14 SET_UPDATE               1
             16 CALL_FUNCTION            1
             18 COMPARE_OP               2 (==)
             20 POP_JUMP_IF_TRUE        13 (to 26)
             22 LOAD_ASSERTION_ERROR
             24 RAISE_VARARGS            1
        >>   26 LOAD_CONST               1 (None)
             28 RETURN_VALUE
#

also i think SET_UPDATE only works with constant sets

earnest wing
#

righty

#

I might make strict=False the default

#

because bytecode is not immune to breaking changes

#

But a bit of version specific code may be in order

quartz wave
# earnest wing Collection types supported now

i think based on the features you just told me i could whip up a simple DIY with fishhook ```py
from fishhook import hook
from opcode import opmap

@hook(set, name="f")
@property
def f(self):
frame = import('sys')._getframe(1)
if frame.f_code.co_code[frame.f_lasti-2] in {opmap['BUILD_SET'], opmap['SET_UPDATE']}:
return frozenset(self)
else:
raise RuntimeError("set is not constant")

assert {1,2,3,4}.f == frozenset({1, 2, 3, 4})

earnest wing
#

Will property work on NoneType?

#

I think a raw descriptor is required here

#

(specifically, hasattr(type(None), "foo") may call None.foo in an undesirable way)

rugged sparrow
#

@earnest wing did you end up using fishhook or did you write your own hook lib?

rugged sparrow
#
>>> class b:
...     def __init__(s, *a):s.a = a
...     def __enter__(s): return s.a
...     def __exit__(*a):pass
... 
>>> with b(1,2,3) as (a,b,c):pass
... 
>>> a
1
>>> b
2
>>> c
3
>>> ``` you can unpack the result of a context manager's `__enter__` method
#

and then if you hooked object.__setattr__ so that if its passed a specific object as the value it does something special you could make with hook(func) as (int.a, float.b) (if i remember correctly you can return a custom iterator that can unpack an arbitrary amount)

#

!e ```py
import sys, dis
def mrange(start=0, step=1):
f = sys._getframe(1)
inst, oparg = f.f_code.co_code[f.f_lasti: f.f_lasti + 2]
if dis.opname[inst] != 'UNPACK_SEQUENCE':
raise RuntimeError('mrange cannot be used in this context')
yield from range(start, oparg, step)
x, y, z = mrange()
print(x,y,z)

night quarryBOT
#

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

0 1 2
silent notch
#

how to get and to be &&

#

Trying to obfuscate, mainly single or double characters for cars and functions, but: and or etc are required to have spaces and one & is bitwise

rugged sparrow
#

do you mean like a and b would be equivalent to a && b?

amber ravine
sick hound
#

Did it again ๐Ÿคฃ

#

Sorry !

icy wing
#
for _ in range(drop_number[i]):
  s.pop(0)
#

oops

#

anyways

#

I have to pop the first entry in a list drop_number[i] times (yes, I have to use pop). The above way feels like it could use improvement, and I have to allocate memory to _ when I don't need it. Is there anyway to do this in less code?

#

besides the obvious moving the pop up to the same line

#

Can I pop a range?

#

Actually, I don't have to use pop, but I do have to modify the array directly, no assignment

earnest wing
#

For non-special-slotted attributes, is there a difference between fishhook and forbiddenfruit hooking?

rugged sparrow
#

my goal when i wrote fishhook was to do all the func pointer math dynamically so that if new special methods were added the lib would still work. There are a few other small differences (fishhook can handle exceptions)

earnest wing
#

Right yeah

#

Not to have to rely on hardcoded struct layout

rugged sparrow
#

yea

#

the lib i've been working on since goes a step further and just makes python think that the builtin types are modify-able like normal types

#

so that stuff like ```py
int.a = 1
print((1).a == 1) # True

earnest wing
#

ooo

rugged sparrow
#

!e ```py

3.10+ only

from ctypes import c_char

BYTES_HEADER = bytes.basicsize - 1

Py_TPFLAGS_IMMUTABLETYPE = 1 << 8

def sizeof(obj):
return type(obj).sizeof(obj)

def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)

def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER

def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr

def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
return cls_mem

def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE

def lock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE

unlock(int)
int.getitem = lambda s,a:print(s, a)
1[0:1:2]```

night quarryBOT
#

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

001 | <string>:53: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
002 | 1 slice(0, 1, 2)
rugged sparrow
#

@earnest wing this is what i have rn, its 3.10+ only as it uses a new type flag

#

(note that i haven't gone through fully to ensure that leaving a builtin type unlocked doesn't crash)

#

also it hasnt been well tested

earnest wing
#

Oh that's good to know, it's handled on a flag basis

rugged sparrow
#

i believe that flag was added so that extension developers could allow users to add new attributes without needing to allocated their types on the heap

#

it used to be that you needed Py_TPFLAGS_HEAPTYPE to be set in order to write attributes but that changed in 3.10

rugged sparrow
#

@earnest wing slight modification to allocate_structs

#
def allocate_structs(cls):
    cls_mem = getmem(id(cls), sizeof(cls), 'P')
    for subcls in type(cls).__subclasses__(cls):
        allocate_structs(subcls)
    for offset, size in get_structs():
        cls_mem[offset] = cls_mem[offset] or alloc(size)
    return cls_mem```
#

needed to allocate structs in reverse to prevent the subclasses trying to read from cls as structs are being allocated

#

i actually think that may be a bug that fishhook has as well

spark barn
#

Iโ€™ve been wanting to get into making an esolang for a while does anyone have a good tutorial or place to start?

silver olive
#

Is there a place to read about the developer decisions for python, not an RFC, but in more of a guided/blog style? "We tried this, thought it was ok, then we did this, result was X, put it into next release"

#

I guess, an "over the shoulder" view of a python core dev

quartz wave
silver olive
#

Forgot about those. ty

wheat river
#

!e

dusky flower
fiery hare
#
dict, list = list, dict
earnest wing
earnest wing
#

Thank you! c:

night quarryBOT
#

@timber grotto :white_check_mark: Your eval job has completed with return code 0.

hello world
quartz wave
#

!timeit ```py
from fishhook import hook
from opcode import opmap

@hook(set, name="f")
@property
def f(self):
frame = import('sys')._getframe(1)
if frame.f_code.co_code[frame.f_lasti-2] in {opmap['BUILD_SET'], opmap['SET_UPDATE']}:
return frozenset(self)
else:
raise RuntimeError("set is not constant")

```py
{1,2,3,4}.f
night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 2.03 usec per loop
quartz wave
#

!timeit

frozenset({1,2,3,4})
night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

1000000 loops, best of 5: 253 nsec per loop
quartz wave
#

how do we make custom property attributes faster ๐Ÿค”

#

hey python has JUMP_BACKWARD now in the most recent version in the repo

rugged sparrow
#

you could already jump backwards, just had to overflow the index lmao

quartz wave
night quarryBOT
#

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

hello5 hello[1, 2, 3] hello<class 'type'>
quartz wave
#

you didn't need complex forbiddenfruit stuff

west cipher
#

hey wait so

#

can it do globals?

#

like all itters for example

quartz wave
west cipher
#
from forbiddenfruit import curse as mutate
mutate(int, '__iter__', lambda s: iter(range(s)))
mutate(str, '__add__', lambda a, b: str.__add__(a, str(b)))
for t in {map, filter, range, list, tuple, frozenset, set, dict, bytes, bytearray}:
    mutate(t, 'list', lambda s: list(s))
    mutate(t, 'len', lambda s: len(s))
#

cuz i got this

#

does fishhook do it easier/faster or anytthing

#

ah i can't hook into like type and have it effect everything dang

#

which makes sense

quartz wave
rugged sparrow
#

im working on a lib where you can hook object

west cipher
#

oh yea i had to find a fork of cursed

west cipher
#

ill prob switch to fishhook thanks

rugged sparrow
#

as soon as i fix the crash when you make a new class after hooking object lol

west cipher
#

xd

#

hey wait

#

do you know how to like, statically analyze code

#

cuz in my xonsh i had to set up an intercept in it's compiler to add my easy lambda thing ฮป(x + 2)

#

is there some generic way I could, say import some module and that allows you to create functions who can take in arbatary code as args that doesn't get evaluates

#

so I can do AST stuff to it

quartz wave
#

or are you talking about trying to do this ```py
a(from thing import *)

west cipher
#

yea i suppose

rugged sparrow
#

so like a func call like this f(a + b) would call f_handler(ast.parse('a + b'))

west cipher
#

but like i can't make some def a(): where i can do a(x) without x existing

rugged sparrow
#

not without major mods

west cipher
#

dang

rugged sparrow
#

it would still need to parse

west cipher
#

i have that setup in xonsh

#

it took a while to figure it out

rugged sparrow
#

yea stuff like that can be tricky

west cipher
#

so i got maps ฮปt, filters ฮปf, and sorts ฮปs
(ฮปt(x ** 3) | ฮปf(x > 0) | ฮปs(x))(range(10, -10, -1))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

#

which is neat, you can make composit lambdas and stuff

rugged sparrow
#

that is neat

west cipher
#

thanks

#

im kinda hooked on python mods now lol

#
from fishhook import hook as mutate
mutate(int, name='__iter__')(lambda s: iter(range(s)))
mutate(str, name='__add__' )(lambda a, b: a + str(b))
for t in {map, filter, range, list, tuple, frozenset, set, dict, bytes, bytearray}:
    mutate(t, name='list')(lambda s: list(s))
    mutate(t, name='len' )(lambda s: len(s))

@rugged sparrow rate my macros lol

rugged sparrow
#

10/10

west cipher
#

thanks haha

#

also u know of anyway to effect everything with __iter__?

rugged sparrow
#

working on it

#

hooking object.__iter__ should do it

#

but i need to get that stable first

#

found why it crashes, object->tp_base is null (for some reason)

#

so object->tp_base has to be null inorder for base resolution to work

#

but object->tp_base is used without being checked in places that python assumes object will never be (and it crashes there)

#

i might be able to make a fake object class and set that as object->tp_base

rugged sparrow
# west cipher also u know of anyway to effect everything with `__iter__`?

!e ```py
from ctypes import c_char

BYTES_HEADER = bytes.basicsize - 1

Py_TPFLAGS_IMMUTABLETYPE = 1 << 8

def sizeof(obj):
return type(obj).sizeof(obj)

def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)

def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER

def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr

def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
return cls_mem

def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE

def lock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE

def patch_object():
# adds extra fake object class to inheritance chain so that object can be modified safely
obj_mem = getmem(id(object), sizeof(object), 'P')
fake_obj_mem = alloc(sizeof(object))
getmem(fake_obj_mem, sizeof(object), 'B')[:] = obj_mem.tobytes()
tp_base_offset = [*getmem(id(type('',(),{})), sizeof(object), 'P')].index(id(object))
obj_mem[tp_base_offset] = fake_obj_mem

needed to allow for unlock(object) to be stable

patch_object()

unlock(object)
object.iter = lambda s:(yield s)
print(*1)
print(*type)```

night quarryBOT
#

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

001 | 1
002 | <class 'type'>
rugged sparrow
#

got it working, still need to test to ensure its stable but i think it should work

#

@earnest wing ^ got unlock(cls) working

#

3.10+ only tho

quartz wave
#

now i can do some crazy stuff

rugged sparrow
#

im gonna make a small edit so that you can call lock on your own classes properly one sec

#

!e ```py
from ctypes import c_char

BYTES_HEADER = bytes.basicsize - 1

Py_TPFLAGS_IMMUTABLETYPE = 1 << 8

def sizeof(obj):
return type(obj).sizeof(obj)

def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)

def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER

def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr

def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
return cls_mem

def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE

def lock(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE

def patch_object():
# adds extra fake object class to inheritance chain so that object can be modified safely
obj_mem = getmem(id(object), sizeof(object), 'P')
fake_obj_mem = alloc(sizeof(object))
getmem(fake_obj_mem, sizeof(object), 'B')[:] = obj_mem.tobytes()
tp_base_offset = [*getmem(id(type('',(),{})), sizeof(object), 'P')].index(id(object))
obj_mem[tp_base_offset] = fake_obj_mem

needed to allow for unlock(object) to be stable

patch_object()

class a:pass
lock(a)
a.b = 1 # fails```

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 60, in <module>
003 | TypeError: cannot set 'b' attribute of immutable type 'a'
rugged sparrow
#

now lock only changes the flags on the class passed in, and doesn't do any allocation stuff

earnest wing
#

at least, hook(type, name)(descriptor) didn't pass the tests and forbiddenfruit worked

#

I suppose I didn't really try though since curse did exactly what I wanted already lol

earnest wing
#

I could try to reimplement fishhook as one of the backends

earnest wing
#

@rugged sparrow I think I know why I had trouble, fishhook internally applies hooked attributes to a new type(f"{id(cls)}", ...) on a fake inheritance chain, which breaks descriptors

#

so while I had been expecting "test".x to call str.__dict__["x"].__get__(<"test" depending on call type>, str), I get .__get__(<"test" or None>, <class 'fishhook.<id>'>)

#

because the "owner" of the descriptor isn't the hooked class

#

I'll try to work around this using @property if at all possible for now, but just so it's out there

#

because honestly the descriptor protocol is kind of fragile

#

(if it ends up being necessary for disambiguation though, too bad for me I guess)

#

I'll try to add your lock/unlock as an optional 3.10+ backend, though, since it seems the most stable

#

Hmm yeah... with @property, it's impossible to define custom literals on None...

#

I think the original descriptor approach + mro climbing is the way to go

earnest wing
#

... yeah no I think only the way forbiddenfruit hooks its attributes works here

#

the fake inheritance does not play nice with descriptors

earnest wing
rugged sparrow
#

Yea fishhook needs some changes to that inheritance thing

rapid sparrow
#

I am gonns be kicked off this server if I post my code anywhere but here

#
def auto_reload_start(bot):
  import watchdog.observers, watchdog.events
  from pathlib import Path
  from importlib.machinery import all_suffixes
  path_as_dotted = lambda path: list(
    ".".join(p.parts[:-1] + (p.name.removesuffix(s),))
    for p in (
      Path(path).relative_to(Path.cwd()),
    )
    for s in all_suffixes()
    if p.name.endswith(s)
  )
  obs = watchdog.observers.Observer()
  h = type(
    "EvtHandler",
    (watchdog.events.FileSystemEventHandler,),
    {
      "on_modified": lambda self, evt: bot.reload_extension(
        path_as_dotted(evt.src_path)[0]
      ) if path_as_dotted(evt.src_path) else None
    },
  )()
  obs.schedule(event_handler=h, path=Path.cwd() / "commands", recursive=True)
  obs.start()
``` thinkimg whether I should use the Aoril 1 excuse for it existing... nah
west cipher
west cipher
#

btw do you plan to add it to fishhook?

atomic dirge
#

why do i get this?

rugged sparrow
west cipher
icy wing
#

Ugh I've become obsessed with code golfing...

#

I really hope it doesn't affect my normal code lol

vestal solstice
#

it usually does

#

only can hope it brings more good than evil

dark wharf
#

Whenever I want to debug something quickly I always end up writing golfed stuff by instinct, and sometimes that code stays in the final version

earnest stratus
#

[x for y in z for x in y] This syntax is so damn %$%#$# in python, all detached from logic

west cipher
earnest wing
maiden river
maiden river
west cipher
west cipher
#

im aware of it but it just reads so bad

restive void
#

Among worst Python design decisions it's right up there with "def"

runic mirage
#

what is wrong with def?

vestal solstice
#

list comps can have ifs, it's not that easy to reverse

west cipher
#

honestly I wish c style ternary operators were in python, " ? :" is so much smaller than if else

vestal solstice
#

no actually that reads fine
[x for x in y if f(x) for y in z if g(y)]

runic mirage
#

yeah, just skip the first expression and read it after the rest

vestal solstice
#

what no that's how it's now

#

what makes even more sense is to just put the first expression last

#

so it reads how you just said without doing anything

west cipher
vestal solstice
#

yeah

#

well you will stop doing that after you did it a lot

#

but it's natural that this is what you do

west cipher
#

i just don't use that syntax lol

vestal solstice
#

i know

#

it's lifted from haskell, but they dropped the commas

#

you could put the commas back
[for y in z, if g(y), for x in y: x]

restive void
icy wing
#

For some reason, when I do d[i] in this list comprehension, it says i is undefined. Why is this? Am I missing something?

[s.remove(sorted(s)[j]) for j in range(d[i]) for i, s in enumerate(l)]
icy wing
#

oh my god

#

im too tired rn

#

Trying to get this expression onto the same line as the definition, but the problem is it starts with for. Any way around this?

def increment_attendance(s, l):
    for (x, y) in l: s[x][y] += 1
trim grove
#

you could use lambda

icy wing
trim grove
#

show what u tried

icy wing
#
increment_attendance = lambda s, l: for (x, y) in l: s[x][y] += 1
#

apparently my for statement is not a proper expression

#

also, what would the lambda function return?

#

This function just acts on an object

#

It doesn't return anything

#

lambda has to return something iirc

runic mirage
#

This could work, the deque is for consuming the generator

from collections import deque
f = lambda s, l: deque((s[x][y].__iadd__(1) for x, y in l), maxlen=0)```
icy wing
#

I tried __add__ earlier, what's __iadd__?

runic mirage
#

it's the method which gets called when you do +=

icy wing
#

ah

#

that's what I wanted

#

I needed a method to act on the int in order to do the list comprehension

#

add wasn't working

#

thanks

#

Ill try it

#

ugh

#

It's not modifying the entry

#

maaaaaan

#

dude this is killin me

#

it's the last possible line to eliminate

#

The problem is that s[x][y] is an int object and not a pointer to a list entry

runic mirage
#

oh, so it doesn't change the list?

icy wing
#

no, also and int object can't call __iadd__

#

5+=1 doens't make sense I guess

runic mirage
#

oh alright

#
f = lambda s, l: deque((s[x].__setitem__(y, s[x][y] + 1) for x, y in l), maxlen=0)```
#

I hope this equivalent to s[x][y] = s[x][y] + 1

icy wing
#

It works, but now I do face another problem

#

just checked and std library only...

#

frick

runic mirage
#

whoops

icy wing
#

just changed it to list np

#

its fine

#

thanks lightning

trim grove
#
increment_attendance=lambda s,l:[0for x,y in l if s[x].__setitem__(y,s[x][y]+1)]
icy wing
#
increment_attendance=lambda s,l:[s[x].__setitem__(y,s[x][y]+1) for x,y in l]
``` final result
#

wait, gotta remove the spaces

runic mirage
#

is esoteric code allowed

#

because you only use the list for its sideeffect

icy wing
#

yeah, it's fine probably

#

this is an intro level python class and I'm just trying to have some fun with the assignments

#

I'm not turning them in like this lol

#

but people in that class are writing far less efficient code than that

#

I did every function in one line

#
increment_attendance=lambda s,l:[s[x].__setitem__(y,s[x][y]+1) for x,y in l]
drop_lowest=lambda l,d:[s.remove(n[j])for i,s in enumerate(l) if (n:=sorted(s)) for j in range(d[i])]
organize_grades=lambda g,a,m:{s:[g[i]/m[i] for i in range(len(g)) if a[i]==s] for s in ["zy","lab","pa","mid1","mid2","final"]}
gbook_averages=lambda g:{k:sum(v)/len(v) if len(v)>0 else 0 for (k,v) in g.items()}
course_grade=lambda g,w,r:sum([w[k]*g[s if k in r.values() and g[k]<g[(s:=dict(map(reversed,r.items()))[k])] else k] for k in g.keys()])

just for aesthetic

trim grove
#

make them esoteric

icy wing
#

I'm not super familiar with the esoteric lingo

velvet plank
#

!e ```py
=lambda ,:(()for ____ in range(getattr(,'len',)));print((lambda ,:(,))('0',(list,['0','1'])))

night quarryBOT
#

@velvet plank :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 <lambda>
004 | TypeError: 'method-wrapper' object cannot be interpreted as an integer
velvet plank
#

!e ```py
print((lambda ,:(lambda ,:(()for ____ in range(getattr(,'len',))))(,))('0',(lambda ,:(()for ____ in range(getattr(,'len',))))(list,['0','1'])))

night quarryBOT
#

@velvet plank :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 <lambda>
004 | TypeError: 'method-wrapper' object cannot be interpreted as an integer
velvet plank
#

!e ```py
print((lambda ,:(lambda ,:(()for ____ in range(getattr(,'len',lambda:)())))(,))('0',(lambda ,:(()for ____ in range(getattr(,'len',lambda:)())))(list,['0','1'])))

night quarryBOT
#

@velvet plank :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 <lambda>
004 |   File "<string>", line 1, in <lambda>
005 | TypeError: 'generator' object cannot be interpreted as an integer
velvet plank
#

WHAT

split salmon
night quarryBOT
#

Hey @split salmon!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

kind token
#

!e py
?

#

!e
#Trying To Understand 'if' Statements Better
user = input("User:")
useraccount = "User" or "Username"
if user == useraccount:
print("Hello "+user+"!" "\nWelcome!")
else:
print("User Not Found.\nTry Re-entering Your Name")

night quarryBOT
#

@kind token :x: Your eval job has completed with return code 1.

001 | User:Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | EOFError: EOF when reading a line
split salmon
#
print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โ€Š```
trim grove
#

Never Gonna Give You Up

split salmon
#

got a problem with it?

trim grove
#

non printable character

lusty sinew
#

im using python 3.10.4 and pip 22.0.4

velvet plank
#

!e ```py
print((lambda ,:(lambda ,:[()for()in(range)(getattr(,'len',lambda:)())])(,))(print,(lambda ,:[()for()in(range)(getattr(,'len',lambda:)())])(lambda :(print('Output:',) or print and (lambda :print('Output:',))),[[0],[1]])))

night quarryBOT
#

@velvet plank :white_check_mark: Your eval job has completed with return code 0.

001 | Output: 0
002 | Output: 1
003 | 0
004 | 1
005 | [None, None]
velvet plank
#

zamn

velvet plank
#

k

trim grove
#

(fixing it)

lusty sinew
#

pip.main([arg1, arg2])

#

?

trim grove
#

that will give you warnings

lusty sinew
#

yeah

#

i did dir(pip) but didnt find anything else besides main

trim grove
#
__import__("pip._internal.cli.main")._internal.cli.main.main(['install', 'package'])

@lusty sinew try with this

lusty sinew
#

thanks

#

thats great

quartz wave
lusty sinew
quartz wave
#

ok yeah

icy wing
#

When you tell your class discord that you did every method for the assignment in one line and they all say cap, but sharing code will get me banned so I canโ€™t even back it up :(

languid hare
#

!e

from fishhook import hook
@hook(slice)
def __hash__(self): 
  return hash((self.start, self.stop, self.step))

d = {}
d[::-1] = "reversed"
print(d[::-1])
night quarryBOT
#

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

reversed
languid hare
#

hmm

#

@maiden blaze

maiden blaze
#

flosh

elfin wasp
#

this is esoteric enouf? can i join the club?

long hamlet
#

Yeah i think

near gust
#

why does this ad look like such a good shitpost

#

l e a r n d r o n e

vague cairn
#

The idea intrigues me that it might actually be more efficient than just a call to len(), it might depend more on the time it takes to create and store the lambda. Sadly I don't have time to test this out right now.

near gust
#

!e

from typing import TypeVar, Type, ClassVar, Union, Dict, Tuple


def wrap_with_template_args(wrapped, items):
    def wrap(cls):
        template_arg_str = '[' + \
            ', '.join(getattr(i, '__name__', str(i)) for i in items) + ']'
        cls.__name__ = wrapped.__name__ + template_arg_str
        cls.__qualname__ = wrapped.__qualname__ + template_arg_str
        cls.__doc__ = wrapped.__doc__
        return cls
    return wrap


class Template:
    _params: ClassVar[Dict[TypeVar, Type]]

    def __class_getitem__(cls, item: Union[TypeVar, Tuple[TypeVar]]) -> Type:
        if not isinstance(item, tuple):
            item = (item,)

        @wrap_with_template_args(cls, item)
        class _Template:
            def __class_getitem__(
                    cls_, item_: Union[Type, Tuple[Type]]) -> Type:

                if not isinstance(item_, tuple):
                    item_ = (item_,)

                @wrap_with_template_args(cls_, item_)
                class _TemplateInstance(cls_):
                    __class_getitem__ = None  # disable multiple subscripting
                    _params = dict(zip(item, item_))

                return _TemplateInstance

        return _Template


if __name__ == '__main__':
    T = TypeVar('T')
    U = TypeVar('U')

    class Test(Template[T, U]):
        """
        This is a doc
        """

        def __init__(self):
            print("this is a template:", type(self).__name__

    h = Test[int, int]()
    print(h)
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | this is a template: Test[int, int]
002 | <__main__.Test[int, int] object at 0x7f66a12da620>
near gust
#

oops forgot to wrap into a main function

#

I love double nesting of classes

#

when you forget that typing.get_args() exists

fair quartz
#

how do I have decorator like things for primitive types

@required
x = 1

# or any other way to check if var (which cant have an attr) has attr
if x.required:
  ...
def req(var):
  req.x[var.__name__] = 1
  return var
req.x = {}


def check_if_var_is_required(var):
  return var in req.x and req.x[var.__name__]

x = 1
x = req(x)
print(check_if_var_is_required(x))

y = 2
y = req(y)
print(check_if_var_is_required(y))
near gust
#

with the decorator syntax at least

fair quartz
#

how about

#
y = 2
y = req(y)
print(check_if_var_is_required(y))
#

!e

print(*map(chr, map(int, "72 97 114 117 32 68 101 115 117 32 89 111".split())), sep="")
night quarryBOT
#

@fair quartz :white_check_mark: Your eval job has completed with return code 0.

Haru Desu Yo
near gust
#

I see you found my status

#

!e

from typing import Generic, TypeVar, get_args, ClassVar, Tuple, Type


def wrap_template_args(wrapped, items):
    def wrap(cls):
        arg_str = '[' + ', '.join(i.__name__ for i in items) + ']'

        cls.__name__ = wrapped.__name__ + arg_str
        cls.__qualname__ = wrapped.__qualname__ + arg_str
        cls.__doc__ = wrapped.__doc__
        return cls
    return wrap


def template(*args):
    def wrap(cls):
        gen = Generic[tuple(TypeVar("") for i in args)]

        class _Template(cls, gen): 

            def __class_getitem__(_cls, item):
                o = super().__class_getitem__(item)
                template_args = get_args(o)

                @wrap_template_args(_cls, template_args)
                class __Template(o):
                    # expose __args__ to the class
                    __args__: ClassVar[Tuple[Type]] = template_args

                    # also expose the template parameters as a dict
                    _params = dict(zip(args, template_args))

                return __Template
        _Template.__name__ = cls.__name__
        _Template.__qualname__ = cls.__qualname__
        _Template.__doc__ = cls.__doc__

        return _Template
    return wrap


if __name__ == '__main__':
    @template('T', 'U')
    class H:
        def __init__(self):
            print("I'm a template with args:", self._params)
    print(H[int, str]())
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | I'm a template with args: {'T': <class 'int'>, 'U': <class 'str'>}
002 | <__main__.H[int, str] object at 0x7fb504f9ae60>
near gust
#

not sure if static type checkers would like this ยฏ\_(ใƒ„)_/ยฏ

#

!e

print(bytes(map(int, "72 97 114 117 32 68 101 115 117 32 89 111".split())))โ€Š
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

b'Haru Desu Yo'
near gust
#

!e


print(bytes((sum(range((-~True + True) * ~True * ~True)) + sum(range(~True * ~True)), sum(range(-~True * (~True * ~True -~True + True))) - (-~True + True) * ~True, sum(range((~True) ** (-~True) ** (-~True))) - (-~True + True) * -~True, sum(range(True - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, -~True * -~True + True)) + sum(range(-~True * -~True + True)) + sum(range(True - ~True)) - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, (sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True) * -~ True + ~True * ~True, sum(range((-~True * -~True + True + -~True * -~True) * -~True - True)) - sum(range(-~True * -~True + True + -~True * -~True)) + True, sum(range((-~True - ~True) * -~True, sum(range(True - ~True, sum(range(~True * ~True)) + True)))) - sum(range((-~True - ~True) * -~True + True, (-~True - ~True) * -~True - ~True)) - True, sum(range(sum(range(~True * ~True)) + True, sum(range(~True * ~True - ~True)) - ~True)) - ~True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, sum(range((~True) ** (-~True) ** -~True + ~True)) + ~True, sum(range(~True * ~True + True, (~True) ** (-~True) ** -~True)) + True)).decode('utf' + str((-~True) ** (True - ~True))))
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

Haru Desu Yo
languid hare
#

same

sly root
#

lmao

steady falcon
#

Java-level boilerplate lol

class Program_Class():
    def __init__(self):
        return
    def main(self):
        print("hello world")
Program = Program_Class()
if __name__=="__main__":
    Program.main()

near gust
#

I should write a useless library for custom generics that don't only have type parameters

#

basically you can do stuff like
Generic[T, int]

#

and then
Foo[int, 0]

#

and then you can get weird stuff like
Foo[int, {'foo': 'bar', {'bar': 'foo'}}]

#

so that's why they don't exist in the standard library

sly root
#

!e autogenerated py print(bytes((lambda*x:[int(_)for(_)in(x)])(((((93)+(57))-39-(59)+((((60/3)))))),(((((98)+((3)))))),(((((29))))+(((79)))),(((((27)+(65)/5+((68)))))),(((((97)-16+30)))),((((11+(33))))),((((32)))),(((((87))))),(((((45+66))))),((((36+78)))),((((((((61))+(47))))))),((((((79)+((21))))))),((((((55)-71+49))))))))

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

b'Hello, World!'
sly root
#

!e this was generating 2 minutes

print(bytes((lambda*x:[int(_)for(_)in(x)])((((((((3*4)))/(((2)/4/((3))*1)))))),((((((3)-(4-2-5/5))*((1)+((5))))+((5)*4)+5*1*1-4+(4)-2-5-((2)-(3)*4)*5+1+((4))*(5)))),(((((1)*5/((5)/(4)))+(2)/((1))))-((((3)/(4)+5*(3)*(5)/5+((3/2/2)*(2)-(1)/4)))/(3*5-(1+4*4))*(1)*(3*4))),(((((5+4*1-3+(((3)))+5-1*5/(1+4)))+2-4-5-(5)-3+((1+4*(1))*3*4-3-((3))*((2))+4)*(((2)))))),(((((4+(5*(4)+(4))))+1/2/2*2*(1)-((3))/(((4))))*((((4)))))),(((((3*(3+5)+1+(4+1/1)+((5))+(1)))+(((4)))+((4/1))))),((((((4))-2-2*2)-(((((5)))+1)))))-(((2+(2)/(2)*4*2*((1)/(4/3))*((3)/(3-2)))-((((4)*(5*3)))))),((((4)))/3/(2)-2*5-2/3*(3)*(2*5)+((4-(1)))-(((4)+1/1))+(((((1*(2)*2)))))+(((3)/2))-(((5)))-(((1)+5))/2+((2))*((5)+4)+((3))-1/3*1/((2))+1/((1))*((1+1*3))+(((5+(1))*((5))*((4))-(1)-4*5-2-4+(3)/1))),((((((3)*(3*(4*3))+((1)+((1))/1)-((2)-(1+(2)))))))),(((((4))+5*(2)*(5)/(1)*(5))))-((((3+5*3)+4+5*4/(1)*((2/2+5)))+((1)-(3)))),(((1+(5)-(((3)/3)/((2))))+(3+((3))/2)+((4*3+2+(5))-((((4)))))*((3*(1))*2/1+3*1/1/2/5*4)-(((2)+(((4+(4)))))/(1)))),((((((5*((2))*2)))*((((4)))+(5)-4)))),(((2*(3)*(((2)*1))+(((5*5/3))))))+((((2)-4*2+2+4+(1)-5*(4))))/(((1*((1))+(3+(1)*3)*3))/((3)/((4)))/(2)-(4/5+((3)))+(((4/5*3-4-5)))/(3-(4-3-3+5*2+2-5*5))-(((4)*(2)+(2)+1))-2/(1-(5)-(3)+2*1+4)-(5)+4))))```
night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

b'Hello, World!'
near gust
#

I did something similar a long time ago but it decomposed all the way down to unary so that it can create a string of a bunch of Trues combined in weird ways

#

in my thing I didn't use that program

#

I did it by hand

sly root
#
    while True:
      atom = str(RandomExpression(3))
      
      try:
        if eval(atom) == self.target:
          return atom
      except: 
        pass```
#
def enc(_0,_1=[]):
 [_1.append(str(MatchRandomExpression(ord(_3))))for(_3)in _0]
 return("print(bytes((lambda*x:[int(_)for(_)in(x)])(%s)))"%",".join(_1)).replace(" ","")```
#

this kills my python process

str(RandomExpression(3, ["<<", ">>"]))
near gust
#

Mine only did single values at first and could convert short strings in under a second because it used identities like i + 1 = -~i

sly root
#
^C[1]    23785 killed     python -i enc.py```
near gust
#

and it also used factorization

#

i have no idea where that program went

#

I originally made it for a code obfuscation contest

finite blaze
near gust
#

I made a single line parser and calculator

finite blaze
#

do they have a website or something?

sly root
#

my phone can't handle this lol

from random import *

class Expression: pass
class Number(Expression):
  def __init__(self, num):
    self.num = num

  def __str__(self):
    return str(self.num)

class BinaryExpression(Expression):
  def __init__(self, left, op, right):
    self.left = left
    self.op = op
    self.right = right

  def __str__(self):
    return str(self.left) + " " + self.op + " "  + str(self.right)

class ParenthesizedExpression(Expression):
  def __init__(self, exp):
    self.exp = exp

  def __str__(self):
    return "(" + str(self.exp) + ")"

class RandomExpression:
  def __init__(
    self, 
    max_pieces: int = 2,
    literals: list = ["-", "+", "*", "/"]
  ):
    self.max_pieces = max_pieces
    self.literals = literals

  def __repr__(self):
    if random() > self.max_pieces:
      return str(Number(randint(1, 5)))
    elif randint(0, 1) == 0:
      return str(ParenthesizedExpression(
        RandomExpression(self.max_pieces / 1.2, self.literals)
      ))
    else:
      return str(BinaryExpression(
        RandomExpression(self.max_pieces / 1.2, self.literals),
        choice(self.literals),
        RandomExpression(self.max_pieces / 1.2, self.literals)
      ))

class MatchRandomExpression:
  def __init__(self, target: int):
    self.target = target

  def __repr__(self):
    while True:
      atom = str(RandomExpression(3, ["<<", ">>"]))
      
      try:
        if eval(atom) == self.target:
          return atom
      except: 
        pass

def encode(_0, _1=[]):
 [_1.append(str(MatchRandomExpression(ord(_3))))for(_3)in _0]
 return("print(bytes((lambda*x:[int(_)for(_)in(x)])(%s)))"%",".join(_1)).replace(" ","")

print(encode("hello world"))```
#

it just keeps crashing

#

idk why because it uses less literals than before

near gust
#

well technically it wasn't an obfuscation contest, but about guessing who wrote what code, but a major part was obfuscation

sly root
#

!e what if.. ```py
from random import *

class Expression: pass
class Number(Expression):
def init(self, num):
self.num = num

def str(self):
return str(self.num)

class BinaryExpression(Expression):
def init(self, left, op, right):
self.left = left
self.op = op
self.right = right

def str(self):
return str(self.left) + " " + self.op + " " + str(self.right)

class ParenthesizedExpression(Expression):
def init(self, exp):
self.exp = exp

def str(self):
return "(" + str(self.exp) + ")"

class RandomExpression:
def init(
self,
max_pieces: int = 2,
literals: list = ["-", "+", "*", "/"]
):
self.max_pieces = max_pieces
self.literals = literals

def repr(self):
if random() > self.max_pieces:
return str(Number(randint(1, 5)))
elif randint(0, 1) == 0:
return str(ParenthesizedExpression(
RandomExpression(self.max_pieces / 1.2, self.literals)
))
else:
return str(BinaryExpression(
RandomExpression(self.max_pieces / 1.2, self.literals),
choice(self.literals),
RandomExpression(self.max_pieces / 1.2, self.literals)
))

class MatchRandomExpression:
def init(self, target: int):
self.target = target

def repr(self):
while True:
atom = str(RandomExpression(3, ["<<", ">>"]))

  try:
    if eval(atom) == self.target:
      return atom
  except: 
    pass

def encode(_0, _1=[]):
[_1.append(str(MatchRandomExpression(ord(_3))))for(3)in 0]
return("print(bytes((lambda*x:[int(
)for(
)in(x)])(%s)))"%",".join(_1)).replace(" ","")

print(encode("hello world"))```

night quarryBOT
#

@sly root :warning: Your eval job timed out or ran out of memory.

[No output]
near gust
#

a discord server

#

i don't want to give any more information or else somebody might smite me

finite blaze
#

Have you guys ever tried golfing snake?

quartz wave
night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 39
002 |     return f"{Number(randint(1, 5)))}"
003 |                                       ^
004 | SyntaxError: f-string: unmatched ')'
#

@quartz wave :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 43
002 |     return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}"
003 |                                                                                         ^
004 | SyntaxError: f-string: unmatched ')'
#

:incoming_envelope: :ok_hand: applied mute to @quartz wave until <t:1649120619:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 138 newlines in 10s).

river idol
#

!unmute 310263589913100288

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @quartz wave.

quartz wave
river idol
#

It does it in all channels to prevent spam. The newlines rule gets accidentally triggered a lot when people post long blocks of code.

#

I recommend using the pastebin service.

quartz wave
#

i'm evaluating code

#

not showing code

river idol
#

Ah right ok. !eval is really more suited to running small snippets of code to demo a concept than whole scripts.

quartz wave
#

ok so i guess i'll have to one-line the classes

#

most

river idol
quartz wave
#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"

class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass

def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int(
)for(
)in(x)])({','.join(_1)})))"

print(encode("hello world"))

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 13
002 |     return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
003 |                                                                                          ^^
004 | SyntaxError: f-string: unmatched ')'
solar dune
#

That is quite the monstrosity

quartz wave
#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"

class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass

def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int(
)for(
)in(x)])({','.join(_1)})))"

print(encode("hello world"))

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 31, in <module>
003 |   File "<string>", line 28, in encode
004 |   File "<string>", line 28, in <lambda>
005 |   File "<string>", line 23, in __str__
006 |   File "<string>", line 1, in <module>
007 | OverflowError: too many digits in integer
quartz wave
#

what

#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"

class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass

def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int(
)for(
)in(x)])({','.join(_1)})))"

print(encode("a"))

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 31, in <module>
003 |   File "<string>", line 28, in encode
004 |   File "<string>", line 28, in <lambda>
005 |   File "<string>", line 23, in __str__
006 |   File "<string>", line 1, in <module>
007 | OverflowError: too many digits in integer
quartz wave
#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambda
x:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 28, in <module>
003 |   File "<string>", line 26, in encode
004 |   File "<string>", line 26, in <lambda>
005 |   File "<string>", line 22, in __str__
006 |   File "<string>", line 1, in <module>
007 | MemoryError
quartz wave
#

what the hell

#

ok yeah there's no hope for this

vague cairn
#

Is there a way to __import__() specific filenames, possibly named things other than *.py

vague cairn
#

Never mind, this works: ```py
def my_import (filename, globals=None, locals=None, fromlist=None):
with open(filename, 'r') as f:
filecontents = f.read()

if globals is None: globals = {}
if locals is None: locals = {}

exec(filecontents, globals, locals)

#print(globals, locals)
if not fromlist:
    if '__all__' in locals:
        fromlist = locals['__all__']
    else:
        fromlist = [member for member in locals
                    if member[0] != '_']
return {member: locals[member]
        for member in fromlist}
sly root
#

shifting takes more time and memory than normal expression

#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3)
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambda
x:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))

night quarryBOT
#

@sly root :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 28, in <module>
003 |   File "<string>", line 26, in encode
004 |   File "<string>", line 26, in <lambda>
005 |   File "<string>", line 22, in __str__
006 |   File "<string>", line 1, in <module>
007 | ZeroDivisionError: float division by zero
sly root
#

oh

#

!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3)
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambda
x:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

print(bytes((lambda*x:[int(_)for(_)in(x)])((((((4-2)+(3)*(3)*4*(5)/2))))+((((((3+((2)))))))))))
sly root
#

!e ```
print(bytes((lambdax:[int()for()in(x)])((((((4-2)+(3)(3)4(5)/2))))+((((((3+((2)))))))))))

night quarryBOT
#

@sly root :white_check_mark: Your eval job has completed with return code 0.

b'a'
floral meteor
#

is this obfuscated code that generates obfuscated code?

vague cairn
#

Someone was complaining about finding the builtins module again after getting rid of it? What kind of getting rid of it? because this:

__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); g={}; exec('b=__builtins__', g, g)""",g,g)
print(g['__builtins__'])
print(g['b'])

might be a workaround.

#

!e ```py
builtins=None
print(builtins)
g = globals()
print(g['builtins'])
exec("""print(builtins); g={}; exec('b=builtins', g, g)""",g,g)
print(g['builtins'])
print(g['b'])

night quarryBOT
#

@vague cairn :x: Your eval job has completed with return code 1.

001 | None
002 | None
003 | Traceback (most recent call last):
004 |   File "<string>", line 5, in <module>
005 |   File "<string>", line 1, in <module>
006 | TypeError: 'NoneType' object is not subscriptable
vague cairn
#

wait what?

#

!e ```py
print(globals())

night quarryBOT
#

@vague cairn :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)>}
vague cairn
#

!e

__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); gl={}; exec('b=__builtins__', gl, gl); __builtins__ = gl['__builtins__']""",g,g)
print(__builtins__)```
night quarryBOT
#
Missing required argument

code

vague cairn
#

!e

__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); gl={}; exec('b=__builtins__', gl, gl); __builtins__ = gl['__builtins__']""",g,g)
print(__builtins__)
night quarryBOT
#

@vague cairn :x: Your eval job has completed with return code 1.

001 | None
002 | None
003 | Traceback (most recent call last):
004 |   File "<string>", line 5, in <module>
005 |   File "<string>", line 1, in <module>
006 | TypeError: 'NoneType' object is not subscriptable
vague cairn
#

the python bot keeps being different than than I expect.

terse oriole
#

!e

import builtins
class OneLineError(Exception): ...
class _MISSING: ...
class ProxyObject:
  def __init__(self, owner, value):
    self.owner = owner
    self.value = value
  def __getattr__(self, attr):
    self.value = getattr(self.value, attr)
    return self
  def __getitem__(self, *keys):
    self.value = self.value.__getitem__(*keys)
    return self
  def __call__(self, *args, **kwargs):
    self.value = self.value(*args, **kwargs)
    return self
  @property
  def RET_OBJ(self):
    self.owner.last = self.value
    return self.owner
class OneLinerise:
  last = _MISSING
  def __getattr__(self, attr):
    try:
      self.last = getattr(builtins, attr)
    except AttributeError:
      self.last = globals()[attr]
    return self
  def __getitem__(self, keys):
    self.last = self.last.__getitem__(keys)
    return self
  def __call__(self, *args, **kwargs):
    if self.last is _MISSING:
      raise OneLineError
    self.last = self.last(*args, **kwargs)
    return self
  @property
  def save_last(self):
    globals()["_"] = self.last
    return self
  @property
  def print_last(self):
    print(self.last)
    return self
  @property
  def returned(self):
    if self.last is _MISSING:
      raise OneLineError
    return ProxyObject(self, self.last)
  def save_last_as(self, name):
    globals()[name] = self.last
    return self
  def literal(self, literal):
    self.last = literal
    return self
  def set_var(self, var, name=None):
    globals()[name if name is None else "__"] = var

OneLinerise().print("test").literal(10).returned.bit_length().RET_OBJ.save_last_as("bruh").print_last.print(bruh)
night quarryBOT
#

@terse oriole :white_check_mark: Your eval job has completed with return code 0.

001 | test
002 | 4
003 | 4
terse oriole
#

woah it works

#

technically oneline?

#

it works but its an inefficient implementation

rugged sparrow
near gust
#

!e

hh = lambda x: (
    functools := __import__('functools'),
    (fib := functools.lru_cache((lambda x: 
    x if x <= 1 else fib(x - 1) + fib(x - 2)))),
    print([fib(i) for i in range(x)])
)[-1]

print(hh(10))
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
002 | None
near gust
#

I should make a python 3 version of the one-lined python thing

near gust
#

i love abusing walrus

#

!e

main = lambda: (
    class_ := __import__('types').new_class,
    HelloWorld := class_(
        'HelloWorld',
        exec_body=lambda ns: (
            (ns.update({'__init__':
                        lambda self: print("Hello, World!")}
                      ), ns
            )[-1]
        )
    ),
    instance := HelloWorld(),
    print(instance)
)[-1]

main()
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | Hello, World!
002 | <types.HelloWorld object at 0x7f550927eaa0>
marsh void
#

huh

rich hound
#

huh. thats interesting

#

!e

i=lambda n:n%2!=0
print(i(5))
night quarryBOT
#

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

True
rich hound
#

who can make that shorter

#

but can still be used as a function

trim grove
#

!e

print((lambda n:n&1)(5))
night quarryBOT
#

@trim grove :white_check_mark: Your eval job has completed with return code 0.

1
rugged sparrow
#

!E ```py
i=lambda n:n&1
i2=1 .and

print(i(5))
print(i2(5))```

night quarryBOT
#

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

001 | 1
002 | 1
trim grove
#

prob no further optimization

rich hound
#

!E

i=1 .__and__
print(i(4))โ€Š
night quarryBOT
#

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

0
rich hound
#

nice.

#

!E

i=1 .__or__
for z in range(0,10):
    print(i(z))โ€Š
#

o

#

how is that 5

night quarryBOT
#

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

001 | 1
002 | 1
003 | 3
004 | 3
005 | 5
006 | 5
007 | 7
008 | 7
009 | 9
010 | 9
rich hound
#

interesting

earnest wing
#

1 | 4 == 0b001 | 0b100 == 0b101 == 5

rich hound
#

oh

#

ty :)

quartz wave
crimson plover
#

!e
print("I believe this can run code? ")

#

why the trashcan

#

!e
while True: pass

#

HAHAHAHA serves you well

quartz wave
#

this guy having a monologue

near gust
# marsh void huh

so basically what I did was store a bunch of expressions in a tuple and return the one that actually returns a value by getting the last index and I did this twice: once in the import statement, and another time in the exec_body to update the namespace, and then I abused walrus some more to create an instance and print it. A lot shorter than using a Y combinator, but less likely to get you fired

marsh void
#

yeah, all that makes sense
I just found the code kinda funky and fun

coarse void
#

How normal people type "E" :

a = "E" 

How members lf this community do:

a:=(lambda:str(...)[0])()
coarse void
#

Huh?

quartz wave
#

!e ```py
print([[]for[globals()[
chr(6+(79) # use 6 days and 9 weeks in days
#to help us here
+7
4)]]in[[chr(
6+(7*9)
,)[([]==[])^(3&1)]]]]and a)

night quarryBOT
#

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

E
quartz wave
#

@coarse void you do it like this

crimson plover
#

!e
while True: print(1)

night quarryBOT
#

@crimson plover :x: Your eval job has completed with return code 143 (SIGTERM).

001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
011 | 1
... (truncated - too many lines)

Full output: too long to upload

crimson plover
#

!e
import turtle

night quarryBOT
#

@crimson plover :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 "/usr/local/lib/python3.10/turtle.py", line 107, in <module>
004 |     import tkinter as TK
005 |   File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
006 |     import _tkinter # If this fails your Python may not be configured for Tk
007 | ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
crimson plover
#

..........................

#

um

next flame
strange star
#

Binary search with [1, 2, 3, 4, 5, 6, 7, 8, 9] one liner:

(lambda _Y: (lambda binary_search: (lambda x: print(binary_search(x, 5)))([1, 2, 3, 4, 5, 6, 7, 8, 9]))(lambda array, key: [(lambda end, start, x: (lambda _loop1: _loop1(end, start, x))(_Y(lambda _loop1: (lambda end, start, x: ((lambda x: (x if array[x] == key else ((lambda end: _loop1(end, start, x))((x - 1)) if array[x] > key else ((lambda start: _loop1(end, start, x))((x + 1)) if array[x] < key else _loop1(end, start, x)))))(((start + end) // 2))) if start <= end else -1))))(end if "end" in dir() else None, start if "start" in dir() else None, x if "x" in dir() else None) for (start, end) in [(0, (len(array) - 1))]][0]))((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))))
finite blaze
#

what does it do?

rugged sparrow
#
bs=lambda l,v,o=0:(bs(l[i:],v,o+i)if l[i]<=v else bs(l[:i],v,o))if(i:=len(l)//2)else o
``` smaller binary search^
sick hound
#

wtf

quartz wave
#

!e smaller by 2 bytes ```py
bs=lambda l,v,o=0:(v<l[i]and bs(l[:i],v,o)or bs(l[i:],v,o+i))if(i:=len(l)//2)else o
assert(bs(range(1,10),5) == [*range(1,10)].index(5))
assert(bs(range(2,20,2),16) == [*range(2,20,2)].index(16))
print(f"{bs(range(1,10),5)=}")
print(f"{bs(range(2,20,2),16)=}")

night quarryBOT
#

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

001 | bs(range(1,10),5)=4
002 | bs(range(2,20,2),16)=7
vague cairn
#

What's the hook you overload to get missing() type access to 'globals()' not finding things events?

vague cairn
#

Oh, here it is.

vague cairn
#

!e ```py
from ctypes import py_object
import atexit, builtins, sys, dis

def init_missing_hook(dct, func):
"missing var hook by chilaxan"
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class

ob_base_p.value = missing_hook

@atexit.register
def unhook():
    ob_base_p.value = dict
return unhook

def roman(d, k):
"Undefined variables, that are made up of only roman numerals, are interpreted as numbers."
digits = {'M':1000, 'D':500,
'C':100, 'L':50,
'X':10, 'V':5,
'I':1, 'ฤช':1000}
digits.update({k.lower():v for k,v in digits.items()})
total = current_total = current = 0

for digit in k:
    n = digits[digit]#key error if digit is not roman, which is exactly the exception we want to raise.
    if n == current:
        current_total += n
    elif n < current:
        total += current_total
        current_total = n
    elif n > current:
        total -= current_total
        current_total = n
    current = n
else:
    total += current_total
d[k] = total
return total

init_missing_hook(sys._getframe().f_globals, roman)

print(XXII/VVVVXIII)```

night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

-3.142857142857143
vague cairn
#

Thanks Chilaxan.

quartz wave
#

oh

#

how did you think of that

#

oh i get it now

rapid sparrow
#

question

#

how does six override the getattr for their module ๐Ÿง

#

if I just try to count members of each module (with inspect.getmembers), it seems to reliably crash if six is loaded:

>>> [print(k) or print(len(inspect.getmembers(v))) for k,v in sys.modules.items()]
sys
93
builtins
158
_frozen_importlib
59
_imp
21
_thread
24
_warnings
11
#    *snip*
...
six.moves
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "/usr/lib/python3.9/inspect.py", line 351, in getmembers
    value = getattr(object, key)
  File "/usr/local/lib/python3.9/dist-packages/six.py", line 97, in __get__
    result = self._resolve()
  File "/usr/local/lib/python3.9/dist-packages/six.py", line 120, in _resolve
    return _import_module(self.mod)
  File "/usr/local/lib/python3.9/dist-packages/six.py", line 87, in _import_module
    __import__(name)
ModuleNotFoundError: No module named 'tkinter'```
#

and yes I know everyone is inspired by the shameless use of print(x) or ...

#

I'm not concerned about tkinter... I am really wondering what esoteric tricks they are up to so I can both defend myself against and join their secret society

rapid sparrow
quartz wave
#

what

rapid sparrow
#

is it this?

class MovedModule(_LazyDescr):
    def __get__(self, obj, tp):
        result = self._resolve()
        setattr(obj, self.name, result)  # Invokes __set__.
        try:
            # This is a bit ugly, but it avoids running this again by
            # removing this descriptor.
            delattr(obj.__class__, self.name)
        except AttributeError:
            pass
        return result```
#

oops nvm I thought you said "it is a descriptor"

#

six.moves does not appear to be an actual file

#

it's an object pretending to be a module

near gust
#

why would anyone do that

#

actually

#

I might use that idea

umbral prism
#

also whoops forgot to disable the ping

sly root
#

oh lmao its even longer

#

but without walrus is shorter

restive void
#

!e

i=__import__;b,s=i("io").StringIO(),i("sys");s.stdout=b;_,s.stdout=i("this"),s.stderr;print(i("collections").Counter(b.getvalue().replace(" ","").upper()).most_common(1)[0][0])โ€Š
night quarryBOT
#

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

E
rugged sparrow
#

!e ```py
def getattr(key):return key, 1
import main
print(main.a)

night quarryBOT
#

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

('a', 1)
wheat river
#
{'inline': False, 'name': i.text if i.text else '...', 'value': '...' if valid_chars.match(j.text) else j.text if j.text else '...'}
for i, j in zip(soup.find_all('th')[:10], soup.find_all('td')[:10])
urban musk
#

just, why?

split salmon
#

hi

humble rune
#

this is beautiful

#

it brings tears to my eyes