#esoteric-python

1 messages ยท Page 114 of 1

thin trout
#

Interesting

terse mortar
#

K I just simplified it

#

I'm just getting into this decorator thing so yeah

#

!e ```py
@print
@lambda f: f.name
class Hello: ...

night quarryBOT
#

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

Hello
terse mortar
#

Or an alternative:

#

!e ```py
@import
@lambda _: _.name
class hello: ...

proper vault
#

lul

terse mortar
#

It mentioned someone lol

night quarryBOT
#

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

Hello world!
viscid nymph
#

!e

@lambda f:__import__(f.__name__)
class __hello__:...
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

Hello world!
proper vault
#

!e ```py
from operator import attrgetter
@import
@attrgetter('name')
class hello: pass

night quarryBOT
#

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

Hello world!
viscid nymph
#

!e

@print
class __hello__(metaclass=type('',(),{'__str__':'Hello, World!'})):...
#

wait no

#

!e

@print
class __hello__(metaclass=type('',(type,),{'__str__':lambda*a:'Hello, World!'})):...
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

Hello, World!
spice tapir
#

print("can i test commands here?")

#

no?

terse mortar
#

Bruh

#

Ok well you need to have !e before the code

spice tapir
#

!e print("thats something!")

#

cool!

#
if 1==1:
  print("some weird stuff")
else:
  print("interesting")
#

e! ```py
if 1==1:
print("some weird stuff")
else:
print("interesting")

#

oh

#

e! ```
print("something")

deft rock
# spice tapir !e print("thats something!")

It's "!e" but it has to be at the beginning of your message on its own line. The #bot-commands channel is a good place to practice various commands before "doing it live" in one of the other discussion channels.

#

!e

print("hello")
night quarryBOT
#

@deft rock :white_check_mark: Your eval job has completed with return code 0.

hello
spice tapir
#

!e

if 1==1:
  print("thank you!")
else:
  print("oh i cant code")
night quarryBOT
#

@spice tapir :white_check_mark: Your eval job has completed with return code 0.

thank you!
spice tapir
#

XD

vernal quest
#

The best importation around the world ๐Ÿ˜‚ :
import pygame as pygameisincredibleformakevideogamesorsomeotherthingswecanuseitformakefunnyimportation

terse mortar
viscid nymph
terse mortar
verbal canopy
#

how tf lol

chilly grotto
#

Why this no work?

def check_if_table_exists(table):
    cursor.execute('''SELECT to_regclass('public.{}'))'''.format(table))
    r = cursor.fetchall()
    if r[0][0] is None:
        print('Table doesn\'t exist!')
    else:
        print(r)

check_if_table_exists(shtousoh)
#

I'm getting an error that says shtousoh isn't defined

#

But why would it have to be defined if it's the argument to a function

#

oh

#

put quotes around it

#

merp

snow beacon
#

Whenever we 'help', the code looks worse than before.

chilly grotto
#

I solved it

#

I needed to have the argument in quotes, and I had an extra parentheses in there

#

parenthesi?

#

parenthesus?

#

parenthesis

#

is correct

plucky wedge
#

esoteric is meant for esoteric code

#

not random questions/code tests

snow beacon
#

Do other topical channels get people wanting help with their code?

simple crystal
#

tbf I think chilaxan helped me gain the respect of my current python teacher cuz he hates python so when I used pointers to remove functionality from lists I think it made him like me

#

I badgered him several times to take data structures early and he was like "you use python, lists are a crutch, arrays are FIXED SIZE and ONE DATA TYPE"

#

turns out I need discrete math anyway to take classes after data structures at the uni I'll be attending but I'm hoping I can just do independent study or something for discrete and still wish he let me into fuckin data structures

#

but yeah can we hurry this thing up and make python more like haskell faster

#

how can we make recursion less expensive?

snow beacon
#

A decorator that optimises self-recursive tail calls into loops would be interesting, if a little brittle to redefining the variable holding the function.

simple crystal
#

ooh

chilly grotto
#

Sorry guys I'll try to be more esoteric in the future

snow beacon
#

We'll be glad to have you.

chilly grotto
#

Esoteric is kind of subjective btw

snow beacon
#

That's part of its draw.

chilly grotto
#

Well what I mean is, I'm worried that I won't be esoteric enough even if I think I am

#

I don't want to get yelled at again

snow beacon
#

We weren't trying to forbid you from partaking in this channel, we just thought you might have misunderstood its purpose.

chilly grotto
#

I think I did

#

It seems that this channel is more for exposition than for instruction

#

I think I understand that now, unless I'm mistaken

snow beacon
#

We don't currently have good resources for beginners to understand all of the bedlam that goes on in this channel, because it's just easier to learn to code Python well before you starting coding it mischievously. It's easier to break the rules once you know what will break.

chilly grotto
#

True

snow beacon
#

However, like learning to speak a language through immersion, you might discover how to code regular Python better through reading here. At least, that's what I did.

chilly grotto
#

This server is the best resource I've found for getting help when googling and documentation fails me

simple crystal
#

ya I learned python more completely once I knew what was possible

snow beacon
#

I'll make more when I have time.

broken mesa
#

@snow beacon very interesting guide, though so far its still quite basic. what other topics are you planning on covering?

#

any plans on adding types and ctypes stuff? what about class/object based fuckery?

fluid tree
#

How can I emulate a module? I want to make a multi-file module into a single file

snow beacon
snow beacon
fluid tree
fluid tree
#

(No i wont help lol sorry)

snow beacon
earnest wing
#

Parsing strings in general has a lot of fuff to it

#

nested f-strings, escaped newlines, the 2 different DSLs, comments in strings in comments [...], implicit concat,

broken mesa
snow beacon
#

I was envisioning that being a section of the builtins section.

snow beacon
rugged sparrow
night quarryBOT
#

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

Hello world!
abstract oracle
#

how?

#

!e

@__import__
@lambda _: _.__name__
class __hmm__: ...
night quarryBOT
#

@abstract oracle :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | ModuleNotFoundError: No module named '__hmm__'
abstract oracle
#

0.0

#

whaa

violet rune
#

!e
@import
@lambda _: _.name
class hello: ...

night quarryBOT
#

@violet rune :white_check_mark: Your eval job has completed with return code 0.

Hello world!
violet rune
#

what

#

!e
python --version

night quarryBOT
#

@violet rune :x: Your eval job has completed with return code 1.

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

!e
import platform
print(platform.python_version())

night quarryBOT
#

@violet rune :white_check_mark: Your eval job has completed with return code 0.

3.9.4
violet rune
#

!e
import sys
if sys.hexversion >= 0x3000000:
print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))

night quarryBOT
#

@violet rune :white_check_mark: Your eval job has completed with return code 0.

Python 3.x hexversion 0x30904f0 is in use.
viscid nymph
#

!e

@__import__
@__import__('operator').attrgetter('__name__')
class __phello__:0
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

Hello world!
near umbra
#

can you explain how that works lol

snow beacon
#

The class itself is pretty simple. Then it's decorated with the name lambda, which return the class's name instead of the class, "__hello__". The other decorator is __import__ which is a function that takes a string and imports the module with that name. It imports __hello__, which automatically prints Hello world!

naive roost
#

!e ```py
import(import('operator').attrgetter('name')(type('phello', (), {})))

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

Hello world!
naive roost
#

so, I'm going to write the equivalent code

#

!e ```py
from operator import attrgetter
class phello:
pass
name = phello.name
print(name)
import(name) # which is basically import name

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

001 | __phello__
002 | Hello world!
snow beacon
#

__phello__ looks like the package version of the __hello__ module.

viscid nymph
#

That sounds plausible

floral meteor
night quarryBOT
#

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

Hello world!
floral meteor
#

that's what lambdas are for

#

XD

viscid nymph
floral meteor
#

!e so much unoptimised code just

print("Hello World!")
night quarryBOT
#

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

Hello World!
floral meteor
#

!e but i just cant help but

class _(metaclass=lambda*a:type(*a)()):__lt__=print
_<"Greetings, planet"
night quarryBOT
#

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

Greetings, planet
floral meteor
#

!e ```py
class _(metaclass=lambda*a:type(*a[:2],a[2]|{'lt':print})()<a[2]['victim']):victim='Hello World!'

night quarryBOT
#

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

Hello World!
floral meteor
#

that's right, and it worked

#

i merged two dicts using the | operator

nova aspen
#

oh wait it unpacked the first 2 a items

#

that confused me. and i like it

floral meteor
#

!e ```py
class phello(metaclass=lambda*a:import(a[0])):...

night quarryBOT
#

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

Hello world!
floral meteor
#

how about that one?

nova aspen
#

hmm

#

not really

#

just because i have seen similar and i know why __phello__

floral meteor
#

so you know how metaclass works?

nova aspen
#

yeah i just didn't see how you got the name and the bases using a[:2]

floral meteor
#

!e print((a:=[0,1,2,3])[:2])

night quarryBOT
#

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

[0, 1]
floral meteor
#

!e ```py
class _(metaclass=lambda*a:a[2]['victim']|type(*a[:2],a[2]|{a[2]['a'][2]:getattr(globals()['builtins'],a[2]['a2'])})()):
victim,a,a2='Hello World!',[...,...,'ror'],'print'

night quarryBOT
#

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

Hello World!
nova aspen
#

ok.. i will look into this

floral meteor
#

there that's my final edit

nova aspen
#

i might ping you later if i don't figure this out, are you ok with that?

floral meteor
#

k

#

it is extremely obfuscated

floral meteor
#

!e ```py
class _(metaclass=lambda*a:(*a[2],)[2]|type(*a[:2],a[2]|{a[2]['a'][2]:getattr(globals()['builtins'],a[2]['a2'])})()):
phello,a,a2=...,[...,...,'ror'],'import'

night quarryBOT
#

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

Hello world!
floral meteor
#

I obfuscated it harder

limber orchid
#

any way to make this smaller?

#
    matrixReshape=lambda s,m,r,c:m if len(m)*len(m[0])!=r*c else __import__("numpy").reshape(m,(r,c))```
snow beacon
#
matrixReshape=lambda s,m,r,c:m if r*c!=len(m)*len(m[0])else __import__("numpy").reshape(m,(r,c))
```For a start.
#
matrixReshape=lambda s,m,r,c:__import__("numpy").reshape(m,(r,c))if r*c==len(m)*len(m[0])else m
#
from numpy import*
matrixReshape=lambda s,m,r,c:reshape(m,(r,c))if r*c==len(m)*len(m[0])else m
```This also works.
earnest wing
#

if you want to ditch the short circuiting you can also use (a,b)[c]

snow beacon
#
from numpy import*
matrixReshape=lambda s,m,r,c:(m,reshape(m,(r,c)))[r*c==len(m)*len(m[0])]
```I'm unsure this can get any shorter.
limber orchid
#

thanks

#

Wasn't aware of the boolean-index trick

snow beacon
#

I had forgotten about it until Olivia mentioned it, but I might not have thought that numpy.reshape has no side effects.

snow beacon
#
import numpy
matrixReshape=lambda s,m,r,c:(m,numpy.reshape(m,(r,c)))[r*c==len(m)*len(m[0])]
```I'm pretty sure this is the same length.
earnest wing
#

for longer module names (6+) it's worth it even if you use something just once
for 5 chars, it's the same thing

#

s also isn't used

#

but removing that is a breaking change to the api and requires a new major version :>

snow beacon
forest harbor
#

!e

import timeit
print(timeit.timeit("x == y", "x=tuple(range(100)); y=tuple(range(101))"))
print(timeit.timeit("x == y", "x=list(range(100)); y=list(range(101))"))
night quarryBOT
#

@forest harbor :white_check_mark: Your eval job has completed with return code 0.

001 | 0.4361311779357493
002 | 0.042158572003245354
forest harbor
#

^ funfact

viscid nymph
#

Comparison between lists are optimized in a way like this:

class list:
    def __eq__(self, other):
        for x, y in zip(self, other):
            if x is y:
                continue
            if x != y:
                return False
        return True
#

because is is faster than ==

forest harbor
#

nope, that's not the reason

viscid nymph
#

what's the reason then

forest harbor
#

Lists shortcuts comparisions if the lists have different lengths. Tuples do not.

viscid nymph
#

Ah that seems like another reason

forest harbor
#

The reason is "cause ain't nobody comparing tuples of different lengths", but this actually says a lot about the semantics of lists vs tuples.

viscid nymph
#

I'm still right about lists comparison being faster though.

#

!e

import timeit
print(timeit.timeit("x == y", "x=tuple(range(100)); y=tuple(range(100))"))
print(timeit.timeit("x == y", "x=list(range(100)); y=list(range(100))"))

night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | 0.39714665664359927
002 | 0.1722207530401647
proper vault
#

now try it with range(1000, 1100)

viscid nymph
#

!e

import timeit
print(timeit.timeit("x == y", "x=tuple(range(1000, 1100)); y=tuple(range(1000, 1100))"))
print(timeit.timeit("x == y", "x=list(range(1000, 1100)); y=list(range(1000, 1100))"))
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | 1.5638931365683675
002 | 1.862255543936044
viscid nymph
#

!e

print(1000 is 1000)
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True
viscid nymph
#

๐Ÿค”

proper vault
#

!e

a = 999
print(a + 1 is 1000)
night quarryBOT
#

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

001 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
viscid nymph
#

ah right

forest harbor
#

Python only internalises ints 0 to 255 iirc

proper vault
#

python: exposing implementation since 1991

#

I think there is also -3 -2 -1

viscid nymph
#

!e

print(sum(x is y for x, y in zip(range(1000, 1100), range(1000, 1100))))
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

0
viscid nymph
#

makes sense

forest harbor
#

Now the question is why is that comparing tuples is faster?

#

(it's not just because it skips the is comparision)

boreal slate
fossil estuary
#

is there a way to order a list (ascending) without using sorted() or .sort()?

proper vault
#

you can write your own sorting function

fossil estuary
#

And how would i do so

proper vault
#

well, pick a sorting algorithm is step 1

#

selection sort is probably the simplest, quick sort is probably the best that you can reasonably handwrite

fossil estuary
#

ill go for quick sort :)

proper vault
#

radix sort or pigeon hole sort if you have just numbers

pure thorn
#

n00b question, but Google was a bit unclear.. Using gevent, do I have to import gevent.monkey and monkey patch_all before other imports? Or can I do all my imports then monkey patch?

fossil estuary
proper vault
#

sure

forest harbor
#

bogosort would be my pick. you can implement it in 2 or 3 lines.

fossil estuary
#

lol. but its not efficient

viscid nymph
stark fable
#

inclusive

proper vault
#

oh ok

sudden osprey
#
s = set()
while True:
    x = eval('1000')
    if (y:=id(x)) in s:
        break
    s.add(y)
print(len(s))

(not very) random number generator with a sense of russian roulette, it might just run forever, it might always run forever, it might give some random number.

#

Doesn't really seem to work on snekbox on the bot

ebon ingot
#

does this work because eval forces Python to assign a new space in memory for the int generated?

#

I'm guessing it's because a looped eval(literal) can't be optimized like a looped int(literal), but that's just my take

#

also... are there any uses of := that can't be done by regular Python or is it purely syntactic sugar?

viscid nymph
#

one liners

ebon ingot
#

I should have seen that coming

#

so I guess it's just to improve readability in certain cases?

viscid nymph
#

I would say so

sudden osprey
# ebon ingot does this work because `eval` forces Python to assign a new space in memory for ...

pretty much, yeah. If you do

for _ in range(5):
    print(id(1000))

When this is compiled to bytecode, 1000 will be stored as a single constant, if you use dis.dis then you can see it uses LOAD_CONST to load it each time, so it's loading the same thing each time. Because of this you'll get the same number 5 times. You can even work out what this number will be without actually executing the function

def f():
    for _ in range(5):
        print(id(1000))
    
print(id(f.__code__.co_consts[2]))

f() # will print the same id printed above 5 times

when you use eval, it doesn't know to store it as a constant, so creates a new 1000 each time. I think that's right anyway

stark fable
#

it is storing it as a constant, but it's making a new constant in a new code object

#

the reason that py for _ in range(5): print(id(1000)) prints the same number 5 times is that it's the same LOAD_CONST loading the same constant

#

...uhhhh

#

hmm

#

that wasn't supposed to happen

#

oh

#

!e py exec(''' def f(): print(id(1000)) ''') exec(''' def g(): print(id(1000)) ''') f() g()

night quarryBOT
#

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

001 | 139899852728688
002 | 139899852730192
stark fable
#

python is smarter than i expected, so even if you access the same constant from two different places it might optimise that and make them the same constant

#

but if you force them to be compiled separately, they're two different constants

#

!e py import dis exec(''' def f(): print(id(1000)) ''') exec(''' def g(): print(id(1000)) ''') dis.dis(f) dis.dis(g)

night quarryBOT
#

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

001 |   3           0 LOAD_GLOBAL              0 (print)
002 |               2 LOAD_GLOBAL              1 (id)
003 |               4 LOAD_CONST               1 (1000)
004 |               6 CALL_FUNCTION            1
005 |               8 CALL_FUNCTION            1
006 |              10 POP_TOP
007 |              12 LOAD_CONST               0 (None)
008 |              14 RETURN_VALUE
009 |   3           0 LOAD_GLOBAL              0 (print)
010 |               2 LOAD_GLOBAL              1 (id)
011 |               4 LOAD_CONST               1 (1000)
... (truncated - too many lines)

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

stark fable
#

they're still constants

#

but they're different constants

#

because beyond a certain point it becomes impractical to keep track of every 1000 in existence and make sure they're all the same

#

the reason that in other cases they end up being the same 1000 is that the instructions loading the 1000s all end up pointing at the same 1000 to load

#

because when the code is "compiled" into bytecode it does optimisations like that

sudden osprey
#

So it seems any 1000s that end up in the bytecode will be the same, wonder if there are any exceptions to that

#

not sure if that question makes much sense though lol

stark fable
#

if they're in different pieces of bytecode then they'll be different

#

i think within one piece of bytecode they'll always end up the same

fading inlet
#

!e # start parameter: 10
result = text.endswith('geeks.', 10)
print(result)

night quarryBOT
#

@fading inlet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'text' is not defined
fading inlet
#

start parameter starts with 0 or 1

simple crystal
#

!e

____=type('_', (type,),{'__matmul__':__import__})("_",(),{})
__=_=type('_', (type,),{'__matmul__':lambda*_:_[1].__name__})("_",(),{})
@lambda ___:____@___
@lambda*_:__@_[0]
class __phello__:...
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

Hello world!
floral meteor
#

!e ```py
class phello(False,True,metaclass=lambda*:type('',(),{[2][''][0]:getattr(builtins,_[2][''][1])})()@(type('',(),{[2][''][0]:lambda*:__[[1][1]]})()@[[1][0]])):__='matmul','import'

night quarryBOT
#

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

Hello world!
fleet yacht
#

how do i acess a element in a python class by a string variable

snow beacon
earnest wing
#

x.__dict__.__getitem__(attr), probably

#

except for slotted attrs

#

but that's beside the spec

fleet yacht
#

ok switched my implementation but now i am getting powershell yelling at me

#
+ .
+ ~
Missing expression after '.' in pipeline element.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingExpression```
#

why powershell be angry

floral meteor
#

yes.

earnest wing
#

are you in the right channel?

floral meteor
#

!e ```py
class phello('matmul',import,metaclass=lambda*:type('',(),{[1][0]:[1][1]})()@(type('',(),{[1][0]:lambda*:[1]})()@_[0])):...

night quarryBOT
#

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

Hello world!
rugged sparrow
#
>>> def test_reassign():
...     abc = 'Old Value'
...     print(abc) # 'Old Value'
...     locals()['abc'] = 'New Value'
...     print(abc) # 'New Value'
... 
>>> test_reassign()
Old Value
New Value
>>> 
``` i made the `locals()` mapping mutate the actual locals
floral meteor
#

excellent!

#

how'd you manage that?

broken mesa
#

my rough guess: locals is overwritten and does some inspect stuff

rugged sparrow
#

well i did some code that modifies the behavior of frame.f_locals (which is a getter)

#

__builtins__.locals = lambda:sys._getframe(1).f_locals

#

so this is what makes locals work

broken mesa
#

hah, almost correct. locals is overwriten but its just getframe not inspect

rugged sparrow
#

but frame.f_locals now returns a custom object that handles the modification of the fastlocals array

night quarryBOT
#

Hey @rugged sparrow!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

rugged sparrow
#

that is all the code that lets the frame.f_locals trickery work

#

i use the nb_invert slot function because the C function takes one py_object argument, calls __invert__ and returns the result directly

#

and frame didnt have __invert__ already

floral meteor
#

ya now you can replace

@lambda c:c()
class yay:
  def __some_dunder__(self, *a):
     return do_stuff(*a)

with

class yay(metaclass=lambda*a:type(*a)()):__some_dunder__=lambda*a:do_stuff(*a)
rugged sparrow
#

i can yea but i dont feel the need to in this case lol

#

i just needed some singletons with custom reprs

floral meteor
#

... already exists you probably didn't need rec

#

!e print(repr(...))

night quarryBOT
#

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

Ellipsis
floral meteor
#

oh well that has a different repr to its str

rugged sparrow
#

!e ```py
from ctypes import *
from collections.abc import MutableMapping
import sys

base_size = sizeof(c_void_p)
FrameType = type(sys._getframe())

@lambda c:c()
class Null:
def repr(self):
return '<NULL>'

@lambda c:c()
class rec:
def repr(self):
return '...'

class f_locals(MutableMapping):
invert = None
def init(self, frameobj):
self.frameobj = frameobj

def __repr__(self):
    return f'locals({repr({key: rec if value is self else value for key, value in self.items()})})'

def _getlocp(self):
    addr = id(self.frameobj) + FrameType.__basicsize__ - base_size
    buffer = addr.to_bytes(base_size, sys.byteorder)
    loc_p = POINTER(py_object).from_buffer_copy(buffer)
    return loc_p

def __getitem__(self, key):
    names = self.frameobj.f_code.co_varnames
    if key not in names:
        raise KeyError(key)
    loc_p = self._getlocp()
    try:
        return loc_p[names.index(key)]
    except ValueError:
        return Null

def __setitem__(self, key, value):
    names = self.frameobj.f_code.co_varnames
    if key not in names:
        raise KeyError(key)
    loc_p = self._getlocp()
    if value is not Null:
        loc_p[names.index(key)] = value
    else:
        cast(loc_p, POINTER(c_void_p))[names.index(key)] = None

def __delitem__(self, key):
    names = self.frameobj.f_code.co_varnames
    if key not in names:
        raise KeyError(key)
    loc_p = self._getlocp()
    cast(loc_p, POINTER(c_void_p))[names.index(key)] = None

def __iter__(self):
    return iter(self.frameobj.f_code.co_varnames)

def __len__(self):
    return len(self.frameobj.f_code.co_varnames)

def foo():
f_locals(sys._getframe())['abc'] = 'value'
print(abc)
abc = None
foo()

night quarryBOT
#

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

value
rugged sparrow
#

you can use f_locals class outside of the other weirdness to get a mapping that represents a frames locals

rugged sparrow
floral meteor
#

whats wrong with
rec=type('rec',(),dict(__repr__=lambda s:'...'))()?

rugged sparrow
#

nothing

#

i just didnt implement it like that

floral meteor
#

k

#

basicsize is a dunder now?

rugged sparrow
#

yea its on types

#

also my code has a double free bug

#

whoops

floral meteor
#

oof

rugged sparrow
#

figured out where it is

#

POINTER(py_object) doesnt handle python refcounts

floral meteor
#

does the attr module have much use?

rugged sparrow
#

i havent really ever used it

floral meteor
#

!e ```py
import attr
class Test(metaclass=lambda*a:attr.s(type(*a))):
a=attr.ib(4)
t = Test(4)
print(t)
print(dir(t))
print(t.a)

night quarryBOT
#

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

001 | Test(a=4)
002 | ['__attrs_attrs__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
003 | 4
floral meteor
#

so you coulda turned your init function into

@attr.s
class f_locals(MutableMapping):
  __invert__=None
  frameobj=attr.ob()
#

I broke my brain

#

I'm running on my stomach rn, and it says get food, so brb nerds.

#

ok i broke my usb check this out

snow beacon
#

You can still contribute to discussion here if you want, using online Python and so on.

floral meteor
#

"A device attached to the system is not functioning"

snow beacon
floral meteor
#

i deliberately sacrificed that usb i was gonna burn a pop!_os image to it.

#

me nether, im trying to install it

#

burn the disk image! sacrifice the usb! please the os!

#

maybe i should just wipe the usb and start again

#

diskpart says it's unusable OH NO

#

idk but i cant even format it

#

16gb

#

ive attacked this disk from almost every angle

#

maybe i should try booting from it XD it should have pop os on it

#

aight ill git push all my C: drive code

split crown
#

Can itpy if True: pass elif True: pass elif True: pass else: pass #if just one lineinstead ofpy if True: pass elif True: pass elif True: pass else: passif all code line just one line?

cloud fossil
#

yes but that is just the equivalent of pass

split crown
#

ok

bronze escarp
#

@maiden blaze @terse mortar Alright, there's a way you can help the code golf challenges be a thing. The main thing that I don't have time for is to dedicate time to come up with good prompts that are well suited to esoteric-ness/code-golfness. If y'all can help contribute to that I can probably get the challenges going on the staff side

maiden blaze
#

interesting

terse mortar
#

I mean im down, where do you want us to put the suggestions?

bronze escarp
#

You can DM them to me for the time being until I get some better organizing stuff set up

maiden blaze
#

aight

boreal slate
#

with the help of snekbox

bronze escarp
#

@boreal slate I have an idea of what I want it to look like. I just need to properly scope it out and run it past a few admins who had worked on a similar system previously.

boreal slate
#

ok cool!

maiden blaze
fluid tree
viscid nymph
#

hmm why if statements

#

and why print

#

not sure about the operators

stark fable
#

by banning those things do you mean banning them from occurring at all or just banning them from occurring in the conventional way in the program's code

#

i.e. are you allowed to use the value True if you obtain it as 1>0, or grab modules with __import__

ebon ingot
#

hey, was just messing around in code golf when I found this weird thing

#

I've got no idea why lambdaa:chr(1) doesn't throw an error or return any value

#

if it's parsed as a lambda, it should return a function, but it isn't? no clue what python is interpreting this as

#

!e

lambdaa:chr(1)
night quarryBOT
#

@ebon ingot :warning: Your eval job has completed with return code 0.

[No output]
proper vault
#

that is annotating a variable named lambdaa with the annotation chr(1)

#

!e

lambdaa: chr(1)
print(__annotations__)
night quarryBOT
#

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

{'lambdaa': '\x01'}
ebon ingot
#

TIL about annotations in python

#

I'll be off to do some research, thanks @proper vault!

#

does annotation serve any pythonic purpose? i.e. is there any purpose other than type hinting for people reading the code?

proper vault
#

pydantic uses it for models

#

it is not a pure type hint feature, but that is the most popular usage

ebon ingot
#

ah... is it right to say that the idea behind it is to allow extensibility for 3rd party (and also in-house) type validation packages?

#

and for IDEs and stuff

#

or are there bigger plans coming up for type enforcing in pure python?

proper vault
#

no, python will remain duck typed forever

#

there are far too many things where type enforcement just doesn't work soundly for it to be viable

sick hound
#

Basically, setattr needs to add the attribute to the class not the instance.

#

Right. This should work.

class Packet:
    def __init__(self):
        for field_name in self.fields.keys():

            def accessor(self):
                return self.fields[field_name]

            def setter(self, value):
                self.fields[field_name] = value

            setattr(Packet, field_name, property(accessor, setter))

class HandshakePacket(Packet):
    
    fields = {
        'protocol_version': 0,
    }
#

Also not sure why you wanted to eval. I changed those lines as well.

viscid nymph
#

I would actually do setattr(self.__class__, field_name, property(accessor, setter))

fluid tree
viscid nymph
#

Yep, that's why I mentioned it

astral rover
#

Isn't this now a race condition or like invalid state

#

This is a really bad idea

viscid nymph
#

It should be set in __init_subclass__

astral rover
#

Well ig it doesn't change

#

Yeah that's a better idea (init subclass)

viscid nymph
#

woops

drifting grove
#

This may not be the right place to ask this (sorry in advance if its not), but its for something at least somewhat esoteric.
Does anyone know why this works in normal cpython, but in snekbox/!eval gives an error (TypeError: <module '__main__' (built-in)> is a built-in module), and how to make it work in snekbox?

import inspect
import sys
print(inspect.getsource(sys.modules[__name__]))
floral meteor
#

Duck typing goes a long way towards obfuscation

#

I.e. hide a whole bunch of functions in what looks like numeric operations

high garnet
#

and therefore blocked by the sandbox?

rugged sparrow
#

@drifting grove it is due to how snekbox works. all code in snek box is ran as such -> python3 -c "{code}"

drifting grove
#

Oohh

#

Thank you

rugged sparrow
#

!e ```py
from ctypes import *

_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
print(orig_argv)```

night quarryBOT
#

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

['/usr/local/bin/python', '-Squ', '-c', 'from ctypes import *\n\n_argv = POINTER(c_wchar_p)()\n_argc = c_int()\npythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))\norig_argv = _argv[:_argc.value]\nprint(orig_argv)']
rugged sparrow
#

^ the above gets the original input to the python binary so its easy to see how python is started in snekbox

#

you can actually use the __main__ module to fingerprint in what state python code is ran

drifting grove
#

Whoa

#

That's really smart

#

Thank you very much

rugged sparrow
#

no problem, i had the same question a while back

drifting grove
#

Ok
I'm going to abuse this as much as I can (in a good way)

viscid nymph
#

!e

import sys
print(sys.argv)
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

['-c']
viscid nymph
#

Interesting

night quarryBOT
#

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

-2
rugged sparrow
floral meteor
#

Ooh

rugged sparrow
#

that gives the same as the above

floral meteor
#

Hackery

#

87% thru extracting files

#

Two usbs committed to being sacrificed

#

Battery percentage is moving faster than the install percentage

floral meteor
#

Installation failed

#

Right at the end

#

it was at 99%

night quarryBOT
#

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

False
night quarryBOT
#

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

False
snow beacon
#

!e ```py
c = True
from sys import*
globals().setitem(argv[0][1],not eval(argv[0]))
print(c)

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

False
#

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

0
sick hound
#

nice i dont understand anything

snow beacon
# sick hound nice i dont understand anything

sys.argv is a list of all of the command line arguments, in this case ["-c", ...]. globals() is a dictionary of all of the variables in the global scope. If you do globals()["a"] = 1 then a is now 1. globals().__setitem__ is a method that does that. You give it a name and something to set that name to, and it does the setting. sys.argv[0][1] is "c", so it sets the c variable. It sets it to ~eval(argv[0]), which is ~eval("-c"), ~(-c), ~-True, which is basically True - 1. Since Booleans are a subclass of int, True - 1 is 1 - 1 which is 0. So c gets set to 0.

sick hound
#

isnt there the argparse module

#

that can handle arguments

snow beacon
#

I believe it's a wrapper over sys.argv.

#

And I think it would ignore the first argument anyway.

night quarryBOT
#

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

False
simple crystal
#

!e

import sys
print(sys.argv)
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

['-c']
simple crystal
#

hella

frozen holly
#

I wonder if there's a way to do something along the lines of

from * import *
#

But like dynamicly

proper vault
#

!d pkgutil.iter_modules

night quarryBOT
#

pkgutil.iter_modules(path=None, prefix='')```
Yields [`ModuleInfo`](https://docs.python.org/3/library/pkgutil.html#pkgutil.ModuleInfo "pkgutil.ModuleInfo") for all submodules on *path*, or, if *path* is `None`, all top-level modules on `sys.path`.

*path* should be either `None` or a list of paths to look for modules in.

*prefix* is a string to output on the front of every module name on output.

Note

Only works for a [finder](https://docs.python.org/3/glossary.html#term-finder) which defines an `iter_modules()` method. This interface is non-standard, so the module also provides implementations for [`importlib.machinery.FileFinder`](https://docs.python.org/3/library/importlib.html#importlib.machinery.FileFinder "importlib.machinery.FileFinder") and [`zipimport.zipimporter`](https://docs.python.org/3/library/zipimport.html#zipimport.zipimporter "zipimport.zipimporter").

Changed in version 3.3: Updated to be based directly on [`importlib`](https://docs.python.org/3/library/importlib.html#module-importlib "importlib: The implementation of the import machinery.") rather than relying on the package internal [**PEP 302**](https://www.python.org/dev/peps/pep-0302) import emulation.
proper vault
#

just run through this and import

frozen holly
#

So instead of just straight up importing every possible module, if you make a statement like this

math.sqrt(5)

Without importing math, then ittle catch the error and then attempt to import it

#

Hmm

proper vault
#

ah, I think chillaxan made something very similar

#

but it just suggested the module, rather than importing it straight up

frozen holly
#

Ah right

proper vault
#

the general idea is replace globals() with a dict that will import

frozen holly
#

I'm in class rn but I might give it a shot when I get home

earnest wing
#

if you're working inside a class context you can emulate this with a metaclass

frozen holly
#

Even if its kinda already been mostly done

earnest wing
#
class _(AutoImport):
  print(math.sqrt(5))
#

where AutoImport's metaclass overrides __prepare__

#

heck, you could even do something like

class Blah(type):
  @classmethod
  def __prepare__(mc, n, bs): # custom namespace here
  def __new__(mc, n, bs, ns): return bs[0]
class _(metaclass=Blah): ...

=>

class _(_):
  # your code with auto-imports here
#

so the actual class creation is just a wrapper

#

all within the confines of "safe" python code :>

proper vault
#

you could probably use fishhook for this actually

earnest wing
#

dict.__getitem__?

astral rover
#

Can you hook ModuleType.prepare?

drifting grove
#

A quick little thing I came up with to detect if the code is being run in Snekbox in case anyone else needs it for some reason.
snekbox is True if it is run in Snekbox, False otherwise.
There are probably cases when it would give a false positive, but its probably good enough for most things

snekbox=("built-in"in str(__import__("sys").modules[__name__]))
#

It works because sys.modules[__name__] is a builtin in snekbox

viscid nymph
#
>>> import __main__
>>> __main__
<module '__main__' (built-in)>
drifting grove
#

yeah

viscid nymph
#

Or just doing this

> python -c "import __main__; print(__main__)"
<module '__main__' (built-in)>
drifting grove
#

I just assumed it would mainly be used for things that can be run in both snekbox and python, but uses something not in snekbox

#

like

if snekbox:
  # version without internet access or whatever. maybe has example response for reb request or something
else:
  # version for regular python with internet
proper vault
#

that just tests if you are running interactively or from a file as far as I can tell

drifting grove
#

I think that might be what it does

#

But it also detects when its run with python -c "code"

#

which I think is what snekbox does

proper vault
#

yeah, I considered that also interactive

drifting grove
#

ooh

#

ok

#

sorry

proper vault
#

you could use ```py
import sys
sys.argv[0] == '-c'

drifting grove
#

oh

#

๐Ÿคฆ I didn't think of that

#

thats way better

viscid nymph
drifting grove
#

really?

#

And it doesn't even have the word import in it ๐Ÿ™‚

#

so its less obvious what it does

proper vault
#

!e ```py
import os
print('/snekbox/' in os.environ.get('PYTHONPATH', ''))

night quarryBOT
#

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

True
drifting grove
#

dang I guess I should have done my research on how snekbox works

rugged sparrow
drifting grove
#

!e Basic versions of #define and #include ```py
import sys
def process(lines):
imports = []
for line in lines:
if line.strip().startswith('#include'):
imports.append('import '+line.split()[1])
for i in imports:
lines.insert(0,i)
defs = {}
for line in lines:
if line.strip().startswith('#define'):
defs[line.strip().split()[1]] = line.strip().split()[2]
for d in defs:
for i in range(len(lines)):
lines[i] = lines[i].replace(d,defs[d])
return lines

snekbox=("built-in"in str(sys.modules[name]))
if snekbox:
#from chilaxan on discord .gg/python (message link: #esoteric-python message)
from ctypes import POINTER,c_wchar_p,c_int,pythonapi,byref
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
code = _argv[:_argc.value][-1]
else:code = import("inspect").getsource(sys.modules[name])
lines = code.split('\n')
for line in lines:
x = globals().get('x',0) + 1
if line == 'sys.exit()':break
exec('\n'.join(process(lines[x:])))
sys.exit()
#######################################

#include math
#define cake "lie"

print(math.sin(42))
print(cake)

night quarryBOT
#

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

001 | -0.9165215479156338
002 | lie
viscid nymph
#
>>> import sys
>>> sys.modules['discord'] 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'discord'
>>> __import__('discord') 
<module 'discord' from '...\\discord\\__init__.py'>
>>> sys.modules['discord'] 
<module 'discord' from '...\\discord\\__init__.py'>
rugged sparrow
#

Oh I thought you were saying that sys.modules[key] would import key

#

Automatically

viscid nymph
#

Oh, no

viscid nymph
#

!e I'm guessing this is the only way to print hello world with no brackets and no whitespace

__package__='__hello__';from.import*
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

Hello world!
viscid nymph
#

. is __package__

frozen holly
#
import sys
import io

__print = print

class Fake(io.StringIO):
    def write(self, *args, **kwargs):
        pass

def _print(*args, sep=" ", end="\n", file=sys.stdout, flush=False):
    __print(*args, sep=sep, end=end, file=Fake, flush=flush)

def autoimport():
    if __name__ == "__main__":
        with open(__file__, mode="r", encoding="utf-8") as f:
            file = f.read()
        mods = [m.__name__ for m in sys.modules.values() if m]
        a = globals().copy()
        a["__name__"] = "__exec__"
        __builtins__.print = _print
        while True:
            try:
                exec(file, a, locals())
            except NameError as e:
                module = str(e).split("'")[1]
                if module in mods:
                    globals()[module] = __import__(module)
                a = globals().copy()
                a["__name__"] = "__exec__"
            else:
                break
        __builtins__.print = __print
#

so i made this

#

its terrible

#

it doesnt work on snekbox cos it works by reading the file

#

and im pretty sure that if you try and doing something tricky ittle break

#

but it execs the code, catches any errors, and then automatically imports into the globals the required modules

viscid nymph
#

It's the module's package

drifting grove
frozen holly
#

Ooooh

#

And then with that "detect if ur in snekbox" code snippet, then it can work "universally"

#

I would edit it but I'm in bed rn

echo warren
#

just realised that everything isinstance(..., object)

proper vault
#

It's all objects

snow beacon
#

I think that's Python's tagline.

potent comet
#

All classes are also issubclass(..., type). Including type.

rugged sparrow
#

wrote a version that works by hooking globals at runtime

#

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

def init_missing_hook(dct, func):
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 builtinexc(exc, depth=1):
frame = sys._getframe(1 + depth)
addr = id(frame.f_code.co_code) + bytes.basicsize - 1
mem = (c_char * len(frame.f_code.co_code)).from_address(addr)
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc

import warnings, importlib.util
def auto_import(dct, name):
if importlib.util.find_spec(name):
warnings.warn(f'implicitly importing module {name!r}', RuntimeWarning, 3)
mod = import(name)
dct[name] = mod
return mod
else:
return builtinexc(NameError(f'name {name!r} is not defined'), 2)

def implicit_imports():
init_missing_hook(sys._getframe(1).f_globals, auto_import)

implicit_imports()

print(os)
print(math.sin(42))```

night quarryBOT
#

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

001 | <string>:46: RuntimeWarning: implicitly importing module 'os'
002 | <module 'os' from '/usr/local/lib/python3.9/os.py'>
003 | <string>:47: RuntimeWarning: implicitly importing module 'math'
004 | -0.9165215479156338
rugged sparrow
viscid nymph
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | False True
002 | True True
potent comet
#

Right, my mistake, instances of type since it's the metatype.

earnest wing
#

Hmm, can you use fishhook / something or other to un-implement some of the dunders from object, like eq?

rugged sparrow
#

technically yes

earnest wing
#

I guess the question is whether you can do that, but for specific classes

#

I know they're slotted, or something ยฏ_(ใƒ„)_/ยฏ

rugged sparrow
#

if you set the slot function pointers to null then that would effectively disable that dunder

sick hound
#
from ctypes import py_object, c_char
import atexit, builtins, sys, dis

def init_missing_hook(dct, func):
    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 builtinexc(exc, depth=1):
    frame = sys._getframe(1 + depth)
    addr = id(frame.f_code.co_code) + bytes.__basicsize__ - 1
    mem = (c_char * len(frame.f_code.co_code)).from_address(addr)
    mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
    return exc

import warnings, importlib.util
def auto_import(dct, name):
    if importlib.util.find_spec(name):
        warnings.warn(f'implicitly importing module {name!r}', RuntimeWarning, 3)
        mod = __import__(name)
        dct[name] = mod
        return mod
    else:
        return builtinexc(NameError(f'name {name!r} is not defined'), 2)

def implicit_imports():
    init_missing_hook(sys._getframe(1).f_globals, auto_import)

implicit_imports()

print(os)
print(math.sin(42))
floral meteor
#

Windows can run python in safe mode

floral meteor
#

Yaaass I can make runtime error now I just need to mix it with some ordinals

lone gust
frozen holly
sly root
#

Hello, why this not works?

>>> (([()for()in()if()==()])for([()for()in()if()==()])in([()for()in()if()==()])if([()for()in()if()==()])==([()for()in()if()==()]))

SyntaxError: cannot assign to list comprehension

If this works:

>>> ([()for()in()if()==()])

[]
rugged sparrow
#

because you have a for loop where the assignment target (for x <-- in []) is a list comprehension which is invalid

earnest wing
#

!e ```py
def gen(depth: int) -> str:
x = "{0}for()in{0}if{0}"
for _ in range(depth):
x = x.format("(" + x + ")")
return "(" + x.format(())+ ")"

print(gen(0))
print(gen(1))
print(gen(2))

night quarryBOT
#

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

001 | (()for()in()if())
002 | ((()for()in()if())for()in(()for()in()if())if(()for()in()if()))
003 | ((((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if())))for()in(((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if())))if(((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if()))))
earnest wing
#

these all evaluate to [], too

#

obviously the size grows at 3^n, but :>

#

in fact, [*eval(gen(4))] is enough to freeze for a solid few minutes

floral meteor
#

!e ```py
[print(69)for()in((),)]

night quarryBOT
#

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

69
floral meteor
#

Dafuq is this sorcery I just did?

#

!e print([0x00for()in((),(),())])

night quarryBOT
#

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

[15]
floral meteor
#

!e [print(...)for()in((),(),())]

night quarryBOT
#

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

001 | Ellipsis
002 | Ellipsis
003 | Ellipsis
simple crystal
#

wow didn't know () worked in comprehension

#

maybe good for golfing

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

<generator object <genexpr> at 0x7f7dd85276d0>
simple crystal
#

!e

print([()for()in[1]])
night quarryBOT
#

@simple crystal :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 | TypeError: cannot unpack non-iterable int object
floral meteor
#

It doesn't. Stuff like that only works when I do it

simple crystal
#

!e

print([1 for()in[1]])
floral meteor
#

XD

night quarryBOT
#

@simple crystal :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 | TypeError: cannot unpack non-iterable int object
simple crystal
#

!e print([()for()in((),(),())])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[(), (), ()]
simple crystal
#

!e print([0x00for()in((1),(2),(3))])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[15]
simple crystal
#

whoops

floral meteor
#

Lol

simple crystal
#

!e print([()for()in((1),2(),(3))])

night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 | <string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: 'int' object is not callable
floral meteor
#

What advanced mathematical operation is this?

simple crystal
#

lol my gf is talking

floral meteor
#

!e print(*['K'for()in[(),(),()]],sep='')

night quarryBOT
#

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

KKK
simple crystal
#

hard to focus

floral meteor
#

Tell her I said hi

simple crystal
#

!e print([()for()in((1),(2),(3))])

night quarryBOT
#

@simple crystal :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 | TypeError: cannot unpack non-iterable int object
floral meteor
#

You need commas next to the numbers

simple crystal
#

o ya

#

!e print([()for()in((1,),(2,),(3,))])

night quarryBOT
#

@simple crystal :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 | ValueError: too many values to unpack (expected 0)
simple crystal
#

ah okay

#

so it's unpackin

floral meteor
#

Lol, okay just make the tuples empty

simple crystal
#

thought so

#

maybe not usefulf or golf cuz you need the extra 2 parens

#

hmm maybe it's minus 1 byte

floral meteor
#

Empty unpacking works only with empty sequence

simple crystal
#

!e print([()for()in((),)*3])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[(), (), ()]
floral meteor
#

You can use it to repeat an arbitrary command n times instead of using range(n)

simple crystal
#

yeah

floral meteor
#

Which generates a variable each iteration

simple crystal
#

I'm wondering if it saves any bytes

floral meteor
#

But this creates an empty namespace

simple crystal
#

or is at least the same for swag purposes

#

!e print([()for _ in[1]*3])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[(), (), ()]
floral meteor
#

But that needs spaces

simple crystal
#

!e print([()for()in[()]*3])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[(), (), ()]
simple crystal
#

1 byte longer damn

#

oh wait

#

same

#

with list instead of tuple

#

just swag

floral meteor
#

!e ```py
print(len("print([()for()in[()]*3])"))
print(len("print([()for _ in[1]*3])"))

night quarryBOT
#

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

001 | 24
002 | 24
floral meteor
#

Bruh

#

Well I'd say mines memory optimised as it doesn't make an integer literal each run, just an empty array

#

although they're probably the same size

floral meteor
#

anything can be done by instantiating classes

#

cmm

#

!e ```py
import attr
class call:
def new(self,*a,**k):
class wrapper:new=lambda s,f:f(*a,**k)
return wrapper
@call()
class cout:lt,lshift,le,echo=print,lambda s,o:print(end=str(o))or s,lambda s,i:print(*i)or s,print
@call(end=10)
@attr.s
class forloop:
start, end, step = attr.ib(0), attr.ib(1), attr.ib(1)
def func(self):
cout<self.start
return type(self)(self.start+self.step,self.end,self.step)
def del(self):
@call(self.end>=self.start+self.step)
class runif:
def init(s,cond):
if cond:self.func()

night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
floral meteor
#

yas!

night quarryBOT
#

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

[No output]
sick hound
#

damn it

floral meteor
#

wat?

floral meteor
#

Apparently I have python 3.9.2150.1013

tribal moon
#

!e ```
L ,=[(([0x0for(sum([((+0xCor{0j},)[~0b0]&3)&0xDfor[0j]in((-0b1|0b0,),)](0xEor(1,))),)in((0o0,),)][0b0]<<2)+([9for[i]in[[0x0]]][0x0]),)[0o0]]

print(L)```

night quarryBOT
#

@tribal moon :white_check_mark: Your eval job has completed with return code 0.

[69]
south relic
#

How can I add a view port in tkinter for playing YouTube videos?

vague cairn
fluid tree
sly root
#

you have [()]

#

but only () is enough

#

!e py print([()for()in()if()==()])

night quarryBOT
#

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

[]
sly root
#

im using it in my obfuscator for list creation

simple crystal
#

yeah, I needed to nest so I could multiply

#

since it's the same no of bytes I'll use it for swag purposes in golf

#

ofc usually if you want to loop a number of times you multiply a string in an exec in golf

#

!e print([()for()in()*3])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[]
simple crystal
#

vs

#

!e print([()for()in[()]*3])

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[(), (), ()]
simple crystal
#

I want the 3 iterations not the zero haha

earnest wing
#
islist=lambda x:[]==x*0
simple crystal
#

that's the shortest way to check ya

sick hound
naive roost
#

the \ themselves should be escaped. Also, this should go in a general help channel

fluid tree
night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @quick edge until 2021-05-01 18:15 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

terse mortar
# sick hound

Make it a raw string (add r before the quotes, ie r"C:\Users\User\Etc"

candid wraith
#

been doing some tomfoolery as of late:```py

Get any URL

response = ractf.co.uk
print(response.status_code) # => 200

Paths work too!

response = google.com/memery/nested
print(response.status_code) # => 404

Subdomains also work, of course

response = sha256.badssl.com
print(response.status_code) # => 200

Any attribute from requests.Response is supported

This is also valid syntax

print(google.com.text) # => <!DOCTYPE html><html lang=...

rugged sparrow
#

how did you pull that off?

candid wraith
#

using this mess

#
import requests

from ctypes import py_object
import atexit, builtins

class DotAggregator:
    def __init__(self, base):
        self.url = base

    def __getattr__(self, name):
        sentinel = object()
        if getattr(requests.Response(), name, sentinel) is not sentinel:
            return getattr(requests.get(str(self)), name)

        self.url += "." + name

        return self
    
    def __truediv__(self, ext):
        self.url += "/" + str(ext)

        return self

    def __str__(self):
        return "https://" + self.url

def dict_sub(ob_base_p, func):
    class sub(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:return func(self,key)
            finally:ob_base_p.value=__class__
    return sub

ob_base_p=py_object.from_address(id(globals())+8)
ob_base_p.value=dict_sub(ob_base_p,lambda s,k:DotAggregator(k))```
#

come to think of it URLRoot is kinda useless

#

oh well

rugged sparrow
#

ahh you're using globals hooking, clever

candid wraith
#

updated it to remove URLRoot

#

yeah, I do have an older version that doesn't use global hooking, but it unfortunately doesn't support /whatever

rugged sparrow
#
>>> (google.com/a).url
'google.com/https://a'
``` i think there may be an issue
candid wraith
#

aw shucks i forgot that's why i kept urlroot

#

use this older version

#
import requests

from ctypes import py_object
import atexit, builtins

class DotAggregator:
    def __init__(self, base):
        self.url = "https://" + base

    def __getattr__(self, name):
        sentinel = object()
        if getattr(requests.Response(), name, sentinel) is not sentinel:
            return getattr(requests.get(str(self)), name)

        self.url += "." + name

        return self
    
    def __truediv__(self, ext):
        self.url += "/" + str(ext)

        return self

    def __str__(self):
        return self.url

class URLRoot:
    def __init__(self, root):
        self.root = root

    def __str__(self):
        return self.root

    def __getattr__(self, name):
        return DotAggregator(self.root + "." + name) 

def dict_sub(ob_base_p, func):
    class sub(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:return func(self,key)
            finally:ob_base_p.value=__class__
    return sub

ob_base_p=py_object.from_address(id(globals())+8)
ob_base_p.value=dict_sub(ob_base_p,lambda s,k:URLRoot(k))```
simple crystal
#

can you import the function class from somewhere?

#

I can do type(lambda:...) to get it but I was wondering where it is normally

#

it says its module is builtins but I don't see it

#

!e print(type(lambda:...).__module__)

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

builtins
simple crystal
#

!e print('function' in __builtins__.__dict__)

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

False
simple crystal
#

!e print(type(lambda:...).__qualname__)

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

function
simple crystal
#

found it

#

!e

import types
print((types.FunctionType))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

<class 'function'>
snow beacon
simple crystal
#

how does the argdefs argument of function class work?

#

it wants a tuple but I'm not sure what format

simple crystal
#

yeah using exec() is way better than this lol

viscid nymph
#

I don't think you can return though

simple crystal
#

I think it's just a tuple of defaults for args that have to already exist for the code object

#

so when I compile the code object I need to compile a function definition anyway then find the const that is that function and pass that to the function class

#

so might as well just exec()

viscid nymph
#

Or...use def

simple crystal
#

I was trying to figure out how to do what turtle.py does without using exec()

#

i.e. makes all of its public class methods global functions

#

but it seems to be far better to just use exec() like it already does

#

because figuring out which const in the compiled code object is the desired function is a pain

#

and building a code object from scratch is a lot of overhead avoided with exec()

rugged sparrow
#

I wonder why turtle.py doesn't use closures for that

simple crystal
#

ah how would you use closures?

#
## The following mechanism makes all methods of RawTurtle and Turtle available
## as functions. So we can enhance, change, add, delete methods to these
## classes and do not need to change anything here.

__func_body = """\
def {name}{paramslist}:
    if {obj} is None:
        if not TurtleScreen._RUNNING:
            TurtleScreen._RUNNING = True
            raise Terminator
        {obj} = {init}
    try:
        return {obj}.{name}{argslist}
    except TK.TclError:
        if not TurtleScreen._RUNNING:
            TurtleScreen._RUNNING = True
            raise Terminator
        raise
"""

def _make_global_funcs(functions, cls, obj, init, docrevise):
    for methodname in functions:
        method = getattr(cls, methodname)
        pl1, pl2 = getmethparlist(method)
        if pl1 == "":
            print(">>>>>>", pl1, pl2)
            continue
        defstr = __func_body.format(obj=obj, init=init, name=methodname,
                                    paramslist=pl1, argslist=pl2)
        exec(defstr, globals())
        globals()[methodname].__doc__ = docrevise(method.__doc__)

_make_global_funcs(_tg_screen_functions, _Screen,
                   'Turtle._screen', 'Screen()', _screen_docrevise)
_make_global_funcs(_tg_turtle_functions, Turtle,
                   'Turtle._pen', 'Turtle()', _turtle_docrevise)
#

this is what it does

rugged sparrow
#

you just define a function inside the for loop

#

that does what __func_body does

#

and then set globals()[methodname] = new_func

simple crystal
#

oh makes sense

#

I might try to do that later and see if I can get it to work

#

would that be a closure or would the only surviving reference be in globals?

#

o its a closure

simple crystal
#

what's the weirdest thing you can make __new__ do and still return an instance of the class containing it

#

like is there a way without weird monkeypatching to avoid an explicit super().__new__(cls) call in __new__ and still instantiate the class?

#

I'm writing a module that defines a list base class which makes subclasses function like lists i.e. return type self instead of type list when multiplied, concatenated, sliced

simple crystal
#

... there's a UserList in collections >_>

snow beacon
#

object.__new__(cls)?

simple crystal
#

!e

class test(list):
    def __new__(cls):
        return object.__new__(cls)

print(test())
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 3, in __new__
004 | TypeError: object.__new__(test) is not safe, use list.__new__()
simple crystal
#

but yeah that works when inheriting from object directly

#

I should have specified I mean weird stuff to do when constructing subclasses of built in mutable sequences

snow beacon
#

list.__new__(cls)?

simple crystal
#

yeah that also works, doesn't do anything weird though

#
class ListBaseClass(list):
    """Like list if it was meant to be subclassed."""

    def __init(self, n):
        """Set own value and return self."""
        super().__init__(n)
        return self

    def __add__(self, n):
        """Concatenate and return same type as self."""
        return self.__new__(self.__class__).__init(super().__add__(n))

    def __mul__(self, n):
        """Multiply and return same type as self."""
        return self.__new__(self.__class__).__init(super().__mul__(n))

    def __rmul__(self, n):
        """Multiply and return same type as self if left operand doesn't have defined behavior."""
        return self.__mul__(n)

    def __getitem__(self, n):
        """If slicing, return same type as self."""
        if isinstance(n, slice):
            return self.__new__(self.__class__).__init(super().__getitem__(n))
        else:
            return super().__getitem__(n)

better UserList

#

at least, I don't think there's anything UserList does better

#

UserList is picky about __init__ and __new__ of subclasses and this isn't is the main advantage

#

strangely, deque already has all this functionality except obviously slicing

#

subclasses of deque return their own type from add and mul, unlike list, and it's also not picky about __new__ and __init__

astral rover
#

I don't get the point of the UserX stuff in collections

simple crystal
#

well, UserList subclasses return their own type if multiplied, added, sliced

#

list subclasses do not

#

but I think they were originally made before you could actually subclass built-ins

#

the docs say, for example:

The need for this class has been partially supplanted by the ability to subclass directly from list

#

The need for this class has been partially supplanted by the ability to subclass directly from dict

#

etc

#

which implies they were originally for before it was possible

astral rover
#

Oh right

simple crystal
#

!e

class test(list):
    ...
print(type(test()[:]))
from collections import UserList
class test(UserList):
    ...
print(type(test()[:]))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | <class 'list'>
002 | <class '__main__.test'>
astral rover
#

So it's just backwards compatibility

simple crystal
#

that and the subclassing stuff are all I can tell as far as usefulness

#

the docs say it's useful to be able to access their value as an attribute... but imo that's not useful haha

#

UserString is basically a mutable string though

#

well, not rly, but you can replace the string itself inside the object

#

and probably the easiest thing to turn into a fake "mutable string"

frigid wharf
#

is there a way to use contextlib.suppress to suppress StopIteration to make infinite loops?

proper vault
#

not really, the iterator will have already exited by then

#

supress is essentially just except E: pass

rugged sparrow
astral rover
#

Can't you just use itertools.cycle?

austere linden
#

What's this channel for, I meann what does esoteric mean?

#

Wait can u @ me when if someone answers ,lol

#

So I could get a notification

simple crystal
#

is there a better way to get the built-in a sub class inherits from higher in the inheritance chain than self.__class__.__mro__[-2]?

#

with arbitrary number of superclasses in chain

floral meteor
#

@austere linden IT IS CURSED!

solar nimbus
#
parsed = set(
    sum(
        [list(x.keys()) for x in
            [urllib.parse.parse_qs(x) for x in 
                [urllib.parse.urlparse(x).query for x in example_urls]]],
        []
    )
)

๐Ÿ˜ณ

simple crystal
#

ah, the deque implementation is sorta hacky i.e. calls the definitions of its extend and __copy__ for concat and multiply and actually calls __new__ and __init__ on self in __copy__ def instead of directly creating a new one and that's why its subclasses return themselves if concatted or multiplied...

#

I was all excited thinking it'd be possible to make subclasses of built-ins behave by looking at deque but it's rly not worth it to copy this behavior

#

..in C, will continue making a Python module to fix this

#

unless one exists, I searched for a few things on pypi and nothing came up

simple crystal
#

the hardest part: thinking of a name

simple crystal
#

auto_operatio is the best name I can think of cuz operators return Type[self]

#

my dynamic version worked first try (minus testing for mutables which employ slicing which require additional logic) and I must say I have to thank this channel for that

austere linden
night quarryBOT
simple crystal
#

need tests for sets and dicts still

gaunt vessel
#

A weird code I made today generates large lists infinitely.

#This code generates large lists of n-tuples of from v0 to v_(n) (v0>=v1>=v2>=...>=v_(n-1)>=v_(n)>=1)

j=2
while True:
    a=eval(str("[("+"{},"*(j-1)+"{}) for {} in range({})"+" for {} in range(1,{}+1)"*(j-1)+"]").format(*["v"+str(i) for i in range(j)],"v0",str(j+1),*["v"+str(i//2*3-i+1) for i in range(j*2-2)]))
    print(j)
    print(a)
    j=len(a)
gaunt vessel
#

!e

#This code generates large lists of n-tuples of from v0 to v_(n) (v0>=v1>=v2>=...>=v_(n-1)>=v_(n)>=1)

j=2
while True:
    a=eval(str("[("+"{},"*(j-1)+"{}) for {} in range({})"+" for {} in range(1,{}+1)"*(j-1)+"]").format(*["v"+str(i) for i in range(j)],"v0",str(j+1),*["v"+str(i//2*3-i+1) for i in range(j*2-2)]))
    print(j)
    print(a)
    j=len(a)
night quarryBOT
#

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

001 | 2
002 | [(1, 1), (2, 1), (2, 2)]
003 | 3
004 | [(1, 1, 1), (2, 1, 1), (2, 2, 1), (2, 2, 2), (3, 1, 1), (3, 2, 1), (3, 2, 2), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
005 | 10
006 | [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 2), (3, 1, 1, 1, 1, 1, 1, 1, 1, 1), (3, 2, 1, 1, 1, 1, 1, 1, 1, 1), (3, 2, 2, 1, 1, 1, 1, 1, 1, 1), (3, 2, 2, 2, 1, 1, 1, 1, 1, 1), (3, 2, 2, 2, 2, 1, 1, 1, 1, 1), (3, 2, 2, 2, 2, 2, 1, 1, 1, 1), (3, 2, 2, 2, 2, 2, 2, 1, 1, 1), (3, 2, 2, 2, 2, 2, 2, 2, 1, 1), (3, 2, 2, 2, 2, 2, 2, 2, 2, 1), (3, 2, 2, 2, 2, 2, 2, 2, 2, 2), (3, 3, 1, 1, 1, 1, 1, 1, 1, 1), (3, 3, 2, 1, 1, 1, 1, 1, 1, 1), (3, 3, 2, 2, 1, 1, 1, 1, 1, 1), (3, 3, 2, 2, 2, 1, 1, 1, 1, 1), (3, 3, 2, 2, 2, 2, 1
... (truncated - too long)

Full output: too long to upload

gaunt vessel
#

successful.

floral meteor
#
def kill_python(*_):
 import sys,os;os.system("")or sys.stderr.write('\x1b[31mFatal Python error: _Py_MorsObitusDecessus: Python has died.\nPython runtime state: deceased\x1b[0m\r\n')
 import ctypes,random
 while...:ctypes.py_object.from_address(random.randint(111111,id(type("",(),{})())+9)).value=type('DEATH',(type,),{'__del__':lambda*a:a})('death',(),{})

@rugged sparrow is there a way to optimise this crasher algorithm?

#

alright i'll try to make a dot notation globals hack

rugged sparrow
#

You can just segfault with ctypes.string_at(0)

floral meteor
#

ah, thank you

#

would that have the same exit code as the above?

rugged sparrow
#

Probably

floral meteor
#

-1073741819

#

is the exit code

#

0xC000... something

#

!e print(hex(-1073741819))

night quarryBOT
#

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

-0x3ffffffb
floral meteor
#

in a different amount of bits

#

!e print(hex((1<<32)-1073741819))

night quarryBOT
#

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

0x1c0000005
floral meteor
#

negative a billion and a bit

floral meteor
#

!e ```py
a,b,c=1,2,3
if a-3:print(a!=3)
if b-3:print(b!=3)
if c-3:print(c!=3)

#

inequality golfing for integers

snow beacon
#
a,b,c=1,2,3
if a-3:print(1>0)
if b-3:print(1>0)
if c-3:print(1>0)
```Shorter.
floral meteor
#

well yeah, but it isn't demonstrative

#

or the same

snow beacon
#

It does the same thing.

floral meteor
#

it's the LHS that's being golfed

snow beacon
#

print(f"{a!=3=}") might be more demonstrative.

floral meteor
#

!e in that case

a,b,c=1,2,3
if a-3:print(a,'=/=',3)
if b-3:print(b,'=/=',3)
if c-3:3
night quarryBOT
#

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

001 | 1 =/= 3
002 | 2 =/= 3
floral meteor
#

the point is i'm using - instead of !=

#

i.e. ```py
class int:
...
def ne(self,other):
return bool(self-other)
def eq(self,other):
return not self!=other

floral meteor
#

ok, it seems i gotta remove existing dot notation syntax sugar to replace it :/

floral meteor
#

okay, full implementation is proving to be insane.

#

completely separating (getattr, setattr, delattr) and dot notation

#

i think i might have to make it not a struct array, in order to simplify it

#

!e ```py
exit=import("_sitebuiltins").Quitter('ab')
class cursed(metaclass=lambda
a:type(*a)()):
def getattr(self, s):
if s=='exit':exit()
else:return object.getattribute(self,s)
def setattr(self,n,v):
if n=='exit':exit(v)
else:object.setattr(self,n,v)

cursed.exit = 69

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 69.

[No output]
edgy spire
#

!e

[globals().setdefault('x', []).append(e) or e for e in range(5)]

print(x)
night quarryBOT
#

@edgy spire :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 2, 3, 4]
edgy spire
#

@solid basalt a sneaky, self-actualizing listcomp

solid basalt
#

but why

#

oh lmao I just realized this was the esoteric channel

edgy spire
#

assignment operators are so yesteryear

solid basalt
#

That makes me physically ill to look at

floral meteor
#

It sets the default and returns the value, but if it already exists, it just returns the value. Hence that initializes at [], appends 0, then appends 1 thru 4 to the already existing value at x

earnest wing
#

yeah I think we got that

gritty mesa
#

!e

class While:
    ___ = lambda self: ((exec(self.code), globals().update(locals()), 
    type(self)(self.condition, self.code)) if eval(self.condition) else ...)
    def __init__(self, condition, code):
      self.condition = condition
      self.code = code
      
      ((x := getattr(self.__class__, 
      (setattr(self.__class__, (t := "__del__"), lambda ________: (...,...)), 
      t)[1]), setattr(x, "__code__", While.___.__code__)))

    
x = 3
While("x < 50", "x += 3")
print(x)
night quarryBOT
#

@gritty mesa :white_check_mark: Your eval job has completed with return code 0.

51
gritty mesa
#

The new and improved while loop

viscid nymph
#

I like for _ in iter(lambda: cond, False)

#

Or maybe to handle falsy values for _ in iter(lamdba: not cond, True)

earnest wing
#

{*iter(lambda:not cond,1)} is a nice touch

#

avoids constructing a big iterable

viscid nymph
#

If I'm doing a while True would that crash my computer

polar talon
#

hmmmm

#

what about this

cond = 5 == 5

while cond:
  print("True")

or this:

# Checking for 5 = 5
num1 = 5
num2 = 5

try:
  num = (num1 - num2) / (num1 - num2)
except Exception:
  print("They're equal")
#

!e

# Checking for 5 = 5
num1 = 5
num2 = 5

try:
  num = (num1 - num2) / (num1 - num2)
except Exception:
  print("They're equal")
night quarryBOT
#

@polar talon :white_check_mark: Your eval job has completed with return code 0.

They're equal
polar talon
#

Condition checking through exceptions is too underrated, am I right?

#

!e

Checking for 6 = 5

num1 = 6
num2 = 5

try:
num = (num1 - num2) / (num1 - num2)
except Exception:
print("They're equal")
else:
print("Nopity nope, not the same!")

night quarryBOT
#

@polar talon :white_check_mark: Your eval job has completed with return code 0.

Nopity nope, not the same!
peak path
#

damn

polar talon
#

You can use that to make loops too

viscid nymph
#

you could do assert num1-num2

floral meteor
#

Most people come here for their daily dosage of insanity, I come here for my daily dosage of sanity.

simple crystal
#

I use functions that conditionally raise exceptions to pass to input validating functions so they can validate based on the exception raising func

#

way less hassle than passing to a function that returns a bool and dealing with the bool

#

and if I just want an int I can use int as the exception raising function

#

for example

wheat ruin
#

Does anyone know how to do threading

nova gyro
sick hound
#

Hey guys can we assign custom value to True or False in python 3?

astral rover
#

Yes

#

Just not using equals

#

Check the pins

viscid nymph
#

!e

from ctypes import py_object
py_object.from_address(id(True)+8).value = object
print(True)
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

<object object at 0x7fbf4c4b21a0>
rugged sparrow
#

@sick hound @viscid nymph That is not changing the value of true, it is changing the type of True

viscid nymph
#

If you want I could just do

#

!e

from ctypes import py_object
py_object.from_address(id(True)+8).value = object
py_object.from_address(id(True)).value = object()
print(True)
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

<object object at 0x7f443d9fd1a0>
viscid nymph
#

It's the same output though :P

rugged sparrow
viscid nymph
#

I guess so

pale cove
#
    import inspect, base64
    plain_txt = inspect.getsource(caesar_quine)
    encrypted_msg = []
    length = len(plain_txt)

    for i in range(length): encrypted_msg.append(plain_txt[i])

    for e in range(length):
        encrypted_msg[e] = (ord(encrypted_msg[e]))
        encrypted_msg[e] = (encrypted_msg[e] + 3) % 256
        encrypted_msg[e] = bin(encrypted_msg[e])

    print(' '.join(encrypted_msg))```

This is a quine that encrypts itself in a caesar cipher
It prints its results in binary since 0-30 caused issues, and it gave me a few \r characters when I did
#

Im proud of that

snow beacon
#

That's neat. It things me of a program I wrote for the code obfuscation challenge on the server's esoteric challenges repo.

#

It also had a quine and encipherment.

pale cove
snow beacon
#

Not any more. I'm pretty sure the repo is archived.

#

By code obfuscation I mean code that obfuscates code, not just obfuscated code.

terse mortar
terse mortar
lofty tiger
#

I've been having some issues with the PIL fork of pillow, specifically converting from a .eps file to .png or any other commonly used image format. Is that in anyone's area of expertise? I would greatly appreciate any help.

edgy spire
#

you could try opening an help channel

lofty tiger
#

I have, nobody replied.

#

I tried multiple times

snow beacon
#

Are any of those channels still open?

#

Judging by the timestamp, never mind.

#

I only had the first Google result to send anyway.

earnest wing
#

Why is it that None is so much smaller than other objects?

#

Are the struct fields special cased?

simple crystal
#

is it as big as a pointer?

rugged sparrow
#

@earnest wing None is only 2 fields, ref count and object type

#

!e print(None.sizeof())

simple crystal
#

ah still gotta refcount

night quarryBOT
#

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

16
viscid nymph
#

!E

print(object().__sizeof__())
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

16
simple crystal
#

!e print(type.__sizeof__(type))

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

408
simple crystal
#

chunky boi

left remnant
#

https://www.pyimagesearch.com/2016/03/28/measuring-size-of-objects-in-an-image-with-opencv/
I used this code to make a image measuring program. But the thing is, it only measures the image only once(and the same point multiple times when I repeat the code). How can I make this code measure an image at different parts at the same time like what they showed in the website? Am I doing something wrong?

snow beacon
simple crystal
#

I figured out why turtle.py doesn't use a closure to make the methods global functions, it's so the call signature of the new function is the method call signature without self

#

there's no handy way to give an existing function a new call signature so exec is a good way to do it

fluid tree
rugged sparrow
#

The field is still gonna be there tho

floral meteor
#

!e print(str.sizeof('yo mamma'))

night quarryBOT
#

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

57
floral meteor
#

!e print(str.sizeof('a truck'))

night quarryBOT
#

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

56
floral meteor
#

Hmm

#

XD

#

!e (a:=[1])[0]=0; print(a)

night quarryBOT
#

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

[0]
floral meteor
#

!e (a:=[*range(10)])[0]=10;a.append(a.pop(0));
print(a)

night quarryBOT
#

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

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
floral meteor
#

Using augmented assignment and setitem

#

Together

rugged sparrow
#

@floral meteor did you see my code a while ago that abused iterators and gc to make a tuple that contains itself?

floral meteor
#

Hang on I'm on phone

#

!e ```py
a=()
a+=(a,)
print(a)

#

Oh

#

Oof that copies it

#

Ok @rugged sparrow how'd you do it?

floral meteor
#

Y'know I keep thinking while I code why isn't there a getattribute augmented assignment? Other than it being a trinop rather than binop method

floral meteor
#

Oh wait

#

It's binop

#

So I don't have to do

flippity.floppity.funny.looking = flippity.floppity.funny.looking.thing

I would instead do

flippity.floppity.funny.looking .= 'thing'
#

Or is .= a thing already?

#

How do i hack python to make it a thing?

#

It'd dunder as something like __igetattr__

#

And also add an __icall__ while im there

#

!e print(import('sys').version)

night quarryBOT
#

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

001 | 3.9.4 (default, Apr  5 2021, 18:26:27) 
002 | [GCC 8.3.0]
floral meteor
#

I should update python

rugged sparrow
#

!e ```py
import gc

class magic:
def length_hint(self):
return 1

def __iter__(self):
    for obj in gc.get_objects():
        if isinstance(obj, tuple):
            try:0 in obj
            except SystemError:
                yield obj
                break

tup = tuple(magic())
print(tup)```

night quarryBOT
#

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

((...),)
floral meteor
#

Noice

snow beacon
#
tuple(list(tuple(magic()))) # (((...),),)
floral meteor
#

XD

#

!e ```py
import gc
@print
@tuple
@list
@tuple
@list
@tuple
@lambda c:c()
class magic:
def length_hint(self):
return 1

def __iter__(self):
    for obj in gc.get_objects():
        if isinstance(obj, tuple):
            try:0 in obj
            except SystemError:
                yield obj
                break
night quarryBOT
#

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

(((...),),)
floral meteor
#

Don't judge im on phone

#

But why did it stop at two levels?

simple crystal
#

that's what it does for nested containers I think

#

I've run into it in normal usage anyway forgot exactly why ellipses shows up

simple crystal
#

ah

#

!e

some_list = []
some_list.append(some_list)
exec(f'print(some_list{"[0]"*1000})')
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

[[...]]
bold ruin
#

seven thousand line module, one decorator, all it does is add ">" before each print. just an idea

nova gyro
#

nO

gritty mesa
#
class For:
    def __init__(self, items, iterable, code):
        self.items = items
        self.iterable = iterable
        self.code = code

    def __del__(self):
        try:
            item = next(self.iterable)
            exec(f"{self.items} = {item}")
            exec(self.code)
            globals().update(locals())
            type(self)(self.items, self.iterable, self.code)
        except StopIteration:
            pass

For("x, y", enumerate(["hello", "world"]), "print(f'{x}: {y}')")
```Got a nice for loop alternative
restive void
#

Cool. You can also assign it to a value and then trigger it when needed

#
loop = For("x, y", enumerate(["hello", "world"]), "print(f'{x}: {y}')")
...
loop = "go!"
simple crystal
#

!e

y = lambda x:(exec('''
if x > 2:
    globals()["g"]=4
else:
    globals()["g"]=6''', f:={'x':x}) or f["g"])

print(y(2))
print(y(3))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 6
002 | 4
simple crystal
#

ppl whining about lack of multiline lambdas have no ground to stand on

sick hound
#

!e (a:=[1])[0]=0; print(a)

night quarryBOT
#

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

[0]
sick hound
#

!e print("1")

night quarryBOT
#

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

1
sick hound
#

what if i run discord bot on this?

proper vault
#

discord.py isn't installed and you can't access the internet

sick hound
#

oh

sick hound
#

yeee

snow beacon
#

Plus it times out after a while.

floral meteor
floral meteor
earnest wing
#

use the eval to mine for crypto ๐Ÿง 

floral meteor
#

alright it's insanity time

#

how would I optimise this?

def generate(k:int):
  a = []; from threading import Thread
  f = lambda n:a.append(int('9'*n)**99999)
  for i in str(k):Thread(target=f,args=[int(i)]).start()
  while len(a)<len(k.__str__()):...
  return sum(a)
def main(SEED:int, KEY:list[int]):
  mess = str(generate(SEED))
  extract = lambda*a:[mess[i%len(mess)]for i in a]
  result = int(''.join(extract(*KEY)))
  print(result)
floral meteor
#

it thonks for ages then spits this out

>>> main(334467, [25,3856,936784,-65, -67, -5,2244])
6916073
>>> 
#

ooh, and then i can esolangise the result to turn it into a message

#

I am so using this for ENCRYPTION

floral meteor
#

alright this is integerfuck, enjoy

from collections import defaultdict as d
def decode(n):
  l,a,o=len(s:=str(n)),d(int),str();i=p=a[int()];b=[i]*2;c=8;t=0
  while len(s)>=p:
    def _0():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t
    def _1():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operater XDDD
    _2,_3=lambda: +i+ 1,c,o,t,lambda: +i- 1,c,o,t
    _4=lambda:i,c,print(end=chr(a[i])or o+chr(a[i]),t
    def _5():a[i]=ord(__import__('sys').stdin.read(1));return i,c,o,t
    _6,_7=lambda:i,c,o,t+not bool(a[i]),lambda:i,c,o,t-bool(a[i])
    _8,_9=lambda:i,c+1%32,o,t,lambda:i,c-1%32,o,t
    i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9][int(s[p])]()if not t else i,c,o,t -(t >+ 0 and int(s[p])==7)- -(t <+ 0 and int(s[p])==6)
    p+=1-2 *+ (t <- 0) # i run out of fancy augmented operators :/ gimme more!
    if p <- 0 or p>len(s):raise SyntaxError('mismatched 6 or 7')
  return o
#
from collections import defaultdict as d
def generate(k:int,sec=99999):
  a = []; from threading import Thread
  f = lambda n:a.append(int('9'*n)**sec)
  for i in str(k):Thread(target=f,args=[int(i)]).start()
  while len(a)<len(k.__str__()):...
  return sum(a)
def decrypt(SEED:int, KEY:list[int],sec=99999):
  mess = str(generate(SEED,sec))
  extract = lambda*a:[mess[i%len(mess)]for i in a]
  return int(str().join(extract(*KEY)))
def decode(n):
  l,a,o=len(s:=str(n)),d(int),str();i=p=a[int()];c=8;t=0
  while len(s)>=p:
    def _0():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t
    def _1():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operater XDDD
    _2,_3=lambda: +i+ 1,c,o,t,lambda: +i- 1,c,o,t
    _4=lambda:i,c,print(end=chr(a[i])or o+chr(a[i]),t
    def _5():a[i]=ord(__import__('sys').stdin.read(1));return i,c,o,t
    _6,_7=lambda:i,c,o,t+not bool(a[i]),lambda:i,c,o,t-bool(a[i])
    _8,_9=lambda:i,c+1%32,o,t,lambda:i,c-1%32,o,t
    i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9][int(s[p])]()if not t else i,c,o,t -(t >+ int()and int(s[p])==7)- -(t <+ int()and int(s[p])==6)
    p+=1-2 *+ (t <- int()) # i run out of fancy augmented operators :/ gimme more!
    if p <- int() or p>len(s):raise SyntaxError('mismatched 6 or 7')
  return o
def main():
  o = decode(decrypt(334467, [8153,6,-3,273576346,9929, -55, 4, 7, 888,25,3856,936784,-65, -67, -5,2244,24,-24]))
  return o
#

BEHOLD YE MIGHTY AND DESPAIR, FOR EVEN WHEN YOU HAVE THE KEY IT STILL TAKES AGES TO DECRYPT

#

y'know what'll be cool?

>>> a + 1 = 4
>>> print(a)
3
>>> 
#
>>> 2(a + 1) = 8
>>> print(a)
3
>>> 25 - b**2 = a**2
>>> print(b)
4
#

ALGEBRUH ASSIGNMENT

floral meteor
#

i should make a pep8 for algebruh assignment

fierce olive
#

That is some of the most horrific looking Python I've ever seen

#

Where do you get these ideas?

turbid isle
fierce olive
#

Yeah, I'm still trying to make some sense of it lol

turbid isle
#

Still easier to read then Regex tho right? LOL

fierce olive
#

That is true

turbid isle
#

Yes, this is something that I would have to take half a day to just sit down with and have a little whiteboard to really get a good understanding. Definitely worthy of the eso channel for sure! ๐Ÿ’ฏ

fierce olive
#

Its kind of like that M.C Escher painting of the stairs

turbid isle
strange basin
#

!e

print(False == False in [False])
night quarryBOT
#

@strange basin :white_check_mark: Your eval job has completed with return code 0.

True
plush raven
#

damn, this channel is only for python's god

strange basin
#

rather devils ...

#

this channel is mostly python dark arts ducky_devil

potent comet
#

That's comparison operator chaining. It lets you do 4 < x <=28, which means 4 < x and x <= 28.

#

It happens to also work with all the comparison operators, even if it's rather weird to read.

strange basin
#

Exactly, python parses it aspy (False == False) and (False in [False])

snow beacon
#

It is. 1 in [1, 2, 3] is True.

earnest wing
#

binary operators that "should" return booleans according to the object model

viscid nymph
#

!e print(True | False)

night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

True
thin trout
#

Hmm I guess that makes sense

#

It is basically 1 | 0

simple crystal
#

!e print(True | 0)

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

1
simple crystal
#

hmm

proper vault
#

bools implement bitwise ops

simple crystal
#

!e

class p(int):
    def __ror__(self, other):
        print('test')
        return super().__ror__(other)
print(True|p(1))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

1
simple crystal
#

checks for int eh

#

yephttps://github.com/python/cpython/blob/2a031723eefcf6f1d678bbb4f6018610d43623c4/Objects/boolobject.c#L93

night quarryBOT
#

Objects/boolobject.c line 93

bool_or(PyObject *a, PyObject *b)```
simple crystal
#

or rather checks for non-bool and goes to number if it is

night quarryBOT
#

Objects/boolobject.c lines 92 to 98

static PyObject *
bool_or(PyObject *a, PyObject *b)
{
    if (!PyBool_Check(a) || !PyBool_Check(b))
        return PyLong_Type.tp_as_number->nb_or(a, b);
    return PyBool_FromLong((a == Py_True) | (b == Py_True));
}```
rugged sparrow
#

@simple crystal I didn't know the bot did that

viscid nymph
simple crystal
#

nice me neither

snow beacon
floral meteor
#

Ouch wrong reply

#

3 or 4 posts above

earnest wing
#

observe and weep

#

there's a lot of metaclass & stack frame screwing around

#

froze the program
๐Ÿ˜” can't even solve such a simple equation smh

floral meteor
#

LMFAO your trying to solve that one

#

is it on github?

earnest wing
#

not yet

floral meteor
#

;-;

#

that's probably the most abstracted simultaneous equation solver in existence XD

#

wait how does _(Solver) do metaclass?

#

this looks straight up hacky

earnest wing
#

it is

floral meteor
#

I'd almost say you made your own syntax sugar

#

what if there are multiple solutions, what does it do?

earnest wing
#

pick whatever z3 picks

floral meteor
#

so just pick the first set of coordinates that work?