#esoteric-python

1 messages Β· Page 147 of 1

rich hound
#

yea

#

doesnt help that i cant access the url

quartz wave
#

also i can't believe j, n, r, and y are all not taken

rich hound
#

well

#

i mean

quartz wave
#

all the other letters are taken

rich hound
#

yeah

#

same happens if it starts with a number

#

because you cant have a name that starts with one

quartz wave
#

2 is taken??

rich hound
#

probably by someone at xbox

quartz wave
#

ok well i can't reproduce the error

#

probably because i'm in the REPL

#

i'll try with a file

rich hound
#

ok

quartz wave
#

no i also can't

rich hound
#

oh

sick hound
#

if ur down im down

rapid sparrow
#

yeah I couldn't reproduce either

#

but @rich hound honestly you want to use async for this

#

99% of the work is waiting

glass moss
#

wait did you mean reproduce an erorr

#

i think im in the wrong channel mb

quartz wave
#

by the way we should probably ignore that

sly root
#

Hello, is there a way to get siginfo_t (or siginfo->si_addr) directly from python? (like with ctypes)

quartz wave
#

is that a python object by itself

sly root
#
typedef struct {
	int si_signo;
	int si_code;
	union sigval si_value;
	int si_errno;
	pid_t si_pid;
	uid_t si_uid;
	void *si_addr;
	int si_status;
	int si_band;
} siginfo_t;
#

its from sys/siginfo.h

#

I'm just writing a port of google/glog for python so I need it to print info about received signal

#

I already have basic handler but that's not enough

#

Here's example what glog can do if receives SIGSEGV:

*** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
*** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
PC: @           0x412eb1 TestWaitingLogSink::send()
    @     0x7f892fb417d0 (unknown)
    @           0x412eb1 TestWaitingLogSink::send()
    @     0x7f89304f7f06 google::LogMessage::SendToLog()
    @     0x7f89304f35af google::LogMessage::Flush()
    @     0x7f89304f3739 google::LogMessage::~LogMessage()
    @           0x408cf4 TestLogSinkWaitTillSent()
    @           0x4115de main
    @     0x7f892f7ef1c4 (unknown)
    @           0x4046f9 (unknown)
#

I have:

*** Aborted at 1650603124 (unix time) try "date -d @1650603124" if you are using GNU date ***                   
*** SIGSEGV (@0x0) received by PID 11790 (TID 0x7110cde4f8) from PID 11789; stack trace ***```
sly root
quartz wave
#
from ctypes import *

pid_t = c_int
uid_t = c_uint

class sigval(Union):
    _fields_ = [
        ('sival_int', c_int),
        ('sival_ptr', c_void_p),
    ]

class siginfo_t(Structure):
    _fields_ = [
        ('si_signo', c_int),
        ('si_code', c_int),
        ('si_value', sigval),
        ('si_errno', c_int),
        ('si_pid', pid_t),
        ('si_uid', uid_t),
        ('si_addr', c_void_p),
        ('si_status', c_int),
        ('si_band', c_int),
    ]
#

to get a field from the struct do struct_instance.field

#
get_info(&struct_variable)
``` in C is equal to ```py
get_info(byref(struct_variable))
``` in python
sly root
#

Okay, thanks

magic wraith
# rich hound oh

have you tried printing out full traceback instead of just the error text?

quartz wave
#

fatal errors always end abruptly

magic wraith
#

who said its a fatal error?

#

it is _ list index out of range_

quartz wave
#

this

#

this is the real error
the "list index out of range" is to be ignored

magic wraith
#

eh

#

daemon threads be like

long hamlet
#

Code and output using Pure Python library

humble rune
# sick hound if ur down im down

im currently coding a discord bot that runs the python code safely but my crippling OMORI addiction is preventing me from finishing it faster

sick hound
humble rune
sick hound
#

theres many python 'emulators' out there

humble rune
#

i just send the code off to some server and i get the output as data

sick hound
#

just use their private api to run ur code

humble rune
#

oh pog

#

i can do api

sick hound
#

i think repl has an api but ive never looked into it

wheat river
wheat river
long hamlet
#

Make your own wallpaper with math and a pure Python GL

upbeat sonnet
#

!e ```py
def abbrev_name(name):
return '.'.join([''.join([c for c in i if c.isupper()]) for i in name.title().split(' ')])

print(abbrev_name("suck your mom"))```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

S.Y.M
upbeat sonnet
#

fr

sick hound
#

!e ```py
def abbreviate_word(word):
return '.'.join(map(lambda word: word.title()[0], (word.split(' '))))

print(abbreviate_word("suck your mom"))```

night quarryBOT
#

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

S.Y.M
sick hound
#

@upbeat sonnet

sick hound
#

!e ```py
import math

auth_check = 'some guys password' #input('password? ')
finalized = ''.join(map(lambda encrypt: auth_check[encrypt::math.ceil(math.sqrt(len(auth_check)))].replace(' ',''), range(math.ceil(math.sqrt(len(auth_check))))))

if finalized in ('sgpoouarmysdessw', 'example1', 'example2'):
print('Access Granted.')```

night quarryBOT
#

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

Access Granted.
sick hound
humble rune
#

smushed @sick hound

#
import math
a='some guys password'
f,z=''.join(map(lambda e:a[e::math.ceil(math.sqrt(len(a)))].replace(' ',''),range(math.ceil(math.sqrt(len(a)))))),"example"
print('Access Granted.'*f in('sgpoouarmysdessw','%s1'%z,'%s2'%z))
#

cool thing about multiplying strings

#

you can multiply them by 0

#

to make it empty

#

what is this doing exactly though?

#

(ryuga is prolly gonna upload a 10 byte version of this later lmao)

long hamlet
upbeat sonnet
#

i didnt think of that

#

good job

upbeat sonnet
#

!e py egg = "bacon" egg *= 0 print(egg)

night quarryBOT
#

@upbeat sonnet :warning: Your eval job has completed with return code 0.

[No output]
upbeat sonnet
#

what-

#

!e py egg = 'bacon' egg *= 3 print(egg)

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

baconbaconbacon
upbeat sonnet
#

ah icic

night quarryBOT
#
Missing required argument

code

quartz wave
night quarryBOT
#

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

S.Y.M
long hamlet
#

I used to post some eso art ...nao i post it with full source

sick hound
#

spam of arts

night quarryBOT
#
Not in a million years.

No documentation found for the requested symbol.

sick hound
#

!d lambda

night quarryBOT
#

An anonymous inline function consisting of a single expression
which is evaluated when the function is called. The syntax to create
a lambda function is lambda [parameters]: expression

sick hound
#

oh

sick hound
sick hound
#

!e py w='stop yelling man';print('.'.join(i[0]for i in w.upper().split())) # 69 CHARS w='stop yelling man';print(".".join(e[0]for e in w.title().split())) # 69 CHARS w='stop yelling man';print('.'.join(w[0].upper()for w in w.split())) # 69 CHARS a=lambda w:'.'.join(w.title()[0]for w in w.split());print(a("stop yelling man")) # 80 CHARS @quartz wave 😏

night quarryBOT
#

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

001 | S.Y.M
002 | S.Y.M
003 | S.Y.M
004 | S.Y.M
sick hound
#

tried to get it as small as possible but couldnt get it less than 69 chars

#

i will personally congratulate anyone that can get in under 69 chars

wheat river
#
w='stop yelling man';print('.'.join(i[0]for i in w.upper().split())) # 69 CHARS

πŸ˜‰

earnest wing
#

same length but cooler

'.'.join(i.upper()for i,*_ in w.split())
# comparing to:
'.'.join(i[0]for i in w.upper().split())
wheat river
#
'.'.join(i.upper()for i in __import__('re').findall(r'\b[a-z]',w))

way longer...

dark cosmos
earnest wing
#

Seems optimal

long hamlet
quartz wave
night quarryBOT
#

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

001 | S.Y.M
002 | S.Y.M
quartz wave
#

lowest is 62 chars

long hamlet
# sick hound bro that is trippy

Not that hard to make trippy art see the code....then check the library...done this before in JS but they one off art nao a framework for trippy art lmao

humble rune
#

into wanting to use python_bmp

sick hound
#

oh...

#

it only works with 2 words strings 😭

#
w='stop yelling man'.split();print('.'.join(i[0]for i in w))
#

is 60

sick hound
#
print(*(i[0].upper()for i in'stop yelling man'.split()))

56

quartz wave
# sick hound r u sure?

the requirement is that it's joined by dots and all the letters in the result are uppercase

#

@sick hound your code fits neither of those requirements ```py

w='stop yelling man'.split();print('.'.join(i[0]for i in w)) # should be uppercase
s.y.m
print(*(i[0].upper()for i in'stop yelling man'.split())) # should be joined by dots
S Y M

sick hound
#

but now i know that print(* exists

#

thanks

#

next challenge is to print hello world with no strings and using only in-built libraries πŸ˜‚

languid hare
#

map chr a list of numbers

sick hound
#

lemme try

languid hare
#

!e

print(*map(chr, [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]), sep=chr(1).split(chr(1))[0])
night quarryBOT
#

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

hello, world!
sick hound
#

!e py print(''.join(chr(i)for i in [104,101,108,108,111,32,119,111,114,108,100]))

night quarryBOT
#

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

hello world
sick hound
#

technically theres a string in mine

languid hare
#

yea i had the same issue

#

chr(1).split(chr(1))[0] => ''

sick hound
#

ah

#

very smart

night quarryBOT
#

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

Hello world!
quartz wave
#

easy hello world

#

no strings

sick hound
night quarryBOT
#

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

123
sick hound
#

str() = '' lmao

languid hare
#

there was a lapse in judgement

sick hound
#

overthinking gets the best of us

sick hound
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Hello world!
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 |   File "/usr/local/lib/python3.10/inspect.py", line 1147, in getsource
005 |     lines, lnum = getsourcelines(object)
006 |   File "/usr/local/lib/python3.10/inspect.py", line 1129, in getsourcelines
007 |     lines, lnum = findsource(object)
008 |   File "/usr/local/lib/python3.10/inspect.py", line 940, in findsource
009 |     file = getsourcefile(object)
010 |   File "/usr/local/lib/python3.10/inspect.py", line 817, in getsourcefile
011 |     filename = getfile(object)
... (truncated - too many lines)

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

sick hound
#

ugh i hate how python is built sometimes

quartz wave
#

__hello__ is a frozen module

sick hound
#

sucks

#

so im guessing thats made in c# or whatever language python is made in

quartz wave
#

but it is frozen some time in the building process

sick hound
#

How do i make a like bot on TikTok using proxies Pls help me Ping me

tawny carbon
#

!rule 5

night quarryBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

sick hound
sharp kestrel
#

!silence

night quarryBOT
#

βœ… silenced current channel for 10 minute(s).

sharp kestrel
#

if the topic is dead, revive it with relevant discussion, don't just post drivel

#

!unsilence

night quarryBOT
#

βœ… unsilenced current channel.

humble rune
#

nobody participates here except for me ryuga and 3 other dudes plus some random guy asking for code help

#

this place is dead

#

some guy even posted this before

sharp kestrel
#

then report it to moderation team via modmail, my point above still stands

#

no one forces you to participate and our rules always apply

quartz wave
pastel sparrow
#

occasionally me too

long hamlet
#

Scroll up i post here too

quartz wave
wheat river
#

are type annotations strs in 3.11 alpha?

quartz wave
wheat river
#

πŸ‘

night quarryBOT
#

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

hello world
#

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

[No output]
#

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

hi
#

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

[No output]
finite blaze
#

When I am golfing something

#

I think that this channel is far from being dead

wheat river
#

everybody is welcomed in this channel :)

rapid sparrow
#

!e

def set_tz(
  new_tz: str,
) -> __import__("typing").NamedTuple(
  "TimeState", [["tz", str], ["daylight", int], ["timezone", int], ["tzname", str]]
):
  from ctypes import POINTER, c_char, c_int, c_long, pythonapi
  from os import environ, getenv
  from sys import platform
  if platform == "win32":
    from ctypes import windll
    pythonapi = windll.msvcrt
    pfx = "_"
  else:
    pfx = ""
  tzset = pythonapi[pfx+"tzset"]
  tzset.argtypes = []
  tzset.restype = None
  from collections import namedtuple

  TimeState = namedtuple("TimeState", ["tz", "daylight", "timezone", "tzname"])
  get_time_state = lambda: TimeState(
    getenv("TZ"),
    c_int.in_dll(pythonapi, pfx+"daylight").value,
    c_long.in_dll(pythonapi, pfx+"timezone").value,
    POINTER(c_char * 3).in_dll(pythonapi, pfx+"tzname").contents.value.decode(),
  )
  ts0 = get_time_state()
  environ["TZ"] = new_tz
  tzset()
  ts1 = get_time_state()
  print("Before tzset:", ts0)
  print("After tzset:", ts1)
  return ts1

print(set_tz("EST5EDT"))
print(set_tz("UTC"))```
night quarryBOT
#

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

001 | Before tzset: TimeState(tz=None, daylight=0, timezone=0, tzname='UTC')
002 | After tzset: TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
003 | TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
004 | Before tzset: TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
005 | After tzset: TimeState(tz='UTC', daylight=0, timezone=0, tzname='UTC')
006 | TimeState(tz='UTC', daylight=0, timezone=0, tzname='UTC')
rapid sparrow
#

cross-platform tzset function

#

I needed it because some machines have TZ not set to UTC (grrr)

humble portal
#

!e
import os
os.system("pip install requests")
a = requests.get("https://google.com")
print(a.content[:30])

night quarryBOT
#

@humble portal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | NameError: name 'requests' is not defined
humble portal
#

!e
import os
os.system("pip install requests")
import requests
a = requests.get("https://google.com")
print(a.content[:30])

night quarryBOT
#

@humble portal :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 'requests'
sacred umbra
#

!e Not happening

import os
os.system("python -m pip install requests")
import requests
night quarryBOT
#

@sacred umbra :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 'requests'
humble portal
#

Lol, it was promising tho

sacred umbra
#

They really made sure to make it secure

#

As far as I know they do have some 3rd party libraries already

#

!e

import numpy
print(numpy)
night quarryBOT
#

@sacred umbra :white_check_mark: Your eval job has completed with return code 0.

<module 'numpy' from '/snekbox/user_base/lib/python3.10/site-packages/numpy/__init__.py'>
humble portal
#

Or, what will happen if I use urlib3

sacred umbra
#

Well, try it

wheat river
#

the bot doesn't connect to the net to get the request, so nothing will happen

humble portal
#

Ohh

rapid sparrow
sick hound
#

yo

grave rover
quartz wave
#

not sure why but my decompiler remake is heavily typed

grave rover
#

I gave up on my decompiler

#

making pymixin was giving me enough headaches already

quartz wave
grave rover
#

generators/listcomps and such

#

those were a fucking pain in the ass

quartz wave
#

i can do those fine

#

but branching is really hard

grave rover
#

I'm sure a large part of that is the fact that I'm using an ast visitor and branch-processing which makes it even worse

#

oh branching is easy

quartz wave
#

how

#

i'm using raw bytecode parsing

grave rover
#

you just check if the op is an instance of JumpOp, and then place invisible markers at every place you can jump to

#

ah, I was using my pyasm project for parsing bytecode

quartz wave
#

i can't discern whether i use or/and/conditional expressions/if-statements for stuff

grave rover
#
>>> from asm import *
>>> 
>>> def my_function(x: int = 1) -> int:
...     if x > 20:
...         return x / 20
...     return x
... 
>>> deserializer = Deserializer(my_function.__code__)
>>> deserializer.deserialize()  # Below is formatted for readability
[
    LOAD_FAST(id=124, arg='x'), 
    LOAD_CONST(id=100, arg=20), 
    COMPARE_OP(id=107, arg=4), 
    POP_JUMP_IF_FALSE(id=114, arg=Label(0x7fd2fbeb0d60)), 
    LOAD_FAST(id=124, arg='x'), 
    LOAD_CONST(id=100, arg=20), 
    BINARY_TRUE_DIVIDE(id=27, arg=0), 
    RETURN_VALUE(id=83, arg=0), 
    Label(0x7fd2fbeb0d60), 
    LOAD_FAST(id=124, arg='x'), 
    RETURN_VALUE(id=83, arg=0)
]```
#

having these labels available is incredibly nice to have

quartz wave
#

i could always opt for the if statement

grave rover
#

step 1: split into blocks
step 2: when finding a block, check for JUMP_ABSOLUTE or similar to detect loops

quartz wave
grave rover
#

if not a loop, use if

#

oh did 3.11 change bytecode a lot?

quartz wave
#

like POP_JUMP_BACKWARD_IF_FALSE

grave rover
#

I see

#

that's gonna be fun to work with in my pyasm project PainPeko

quartz wave
# grave rover step 1: split into blocks step 2: when finding a block, check for JUMP_ABSOLUTE ...
>>> dis("while a: b = 3")
              0 RESUME                            0

  1           2 LOAD_NAME                         0 (a)
              4 POP_JUMP_FORWARD_IF_FALSE         6 (to 18)
        >>    6 LOAD_CONST                        0 (3)
              8 STORE_NAME                        1 (b)
             10 LOAD_NAME                         0 (a)
             12 POP_JUMP_BACKWARD_IF_TRUE         4 (to 6)
             14 LOAD_CONST                        1 (None)
             16 RETURN_VALUE
        >>   18 LOAD_CONST                        1 (None)
             20 RETURN_VALUE
>>> dis("if a: b = 3")
              0 RESUME                            0

  1           2 LOAD_NAME                         0 (a)
              4 POP_JUMP_FORWARD_IF_FALSE         4 (to 14)
              6 LOAD_CONST                        0 (3)
              8 STORE_NAME                        1 (b)
             10 LOAD_CONST                        1 (None)
             12 RETURN_VALUE
        >>   14 LOAD_CONST                        1 (None)
             16 RETURN_VALUE
``` hmm yeah i think detecting loops are gonna be much harder
#

ok i think "much harder" is an overestimation

#

i can just check for bytecode[POP_JUMP_FORWARD_IF_FALSE_destination-1].opcode is RETURN_VALUE

#

there's a clear difference between "there's code after it" and "there's no code after it" and it's just the above check

humble rune
#
from random import choice
print("Press the enter key to generate new ones");p,v="hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split("-"),"tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split("-")
while True:input("You %s, ill have you %s"%(choice(p),choice(v)))

can i get a code golfer in the chat

#

πŸ₯Ί

finite blaze
#

You don't have to create variables for p and v

#

@humble rune

humble rune
#
from random import choice
print("Press the enter key to generate new ones")
while True:input("You %s, ill have you %s"%(choice("hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split("-")),choice("tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split("-"))))
finite blaze
#

Don't use -

#

Just do split()

humble rune
#

i can also replace True with 1

humble rune
#
from random import choice
print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split()),choice("tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split())))
finite blaze
#

Replace all - with spaces

#

And remove "replace("-","")"

humble rune
#

wait i dont need that for the first one im dumb

finite blaze
#
from random import choice
print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split())))β€Š
#

Also

#

I think

#

Nvm

humble rune
#
from random import choice;print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".replace("_"," ").split())))

current code

finite blaze
#

Don't need replace

#

Just remove all _

humble rune
#

i need it for "tarred_and_feathered" and "drawn_and_quartered"

finite blaze
#

Remove _

#

And just use spaces

humble rune
#

but then it would split one statement and use them as separate items of the list

wheat river
#
from random import choice;print("Press the enter key to generate new ones");while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split())}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split())}")

just use fstring

humble rune
#

because drawn_and_quartered is one action but if i used spaces it would process it as
["drawn","and","quartered"]

finite blaze
#

But you use replace to put spaces between them

#

So why don't you do it manually?

humble rune
finite blaze
#

Ah now it makes sense

humble rune
#

also for some reason i cant put the while loop with a semicolon after this part from random import choice;print("Press the enter key to generate new ones");

#

so my current code is:

from random import choice;print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split().replace("_"," "))))
finite blaze
#

Might be just a warning

#

Try running it

humble rune
#

anyone know why this says invalid syntax?

#
from random import choice;print("Press the enter key to generate new ones")
while 1:input(f"You {choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split())}, ill have you {choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split().replace("_", " "))}")
finite blaze
#
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split())}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split())}")β€Š
#

You use "" in wrong places

#

And you miss some ' '

humble rune
#
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split().replace("_"," "))}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split().replace("_"," "))}")
#

the replace is needed for rough_neck in the first string and the second string needs it for tarred and feathered and drawn and quartered

#

but it can be shifted to one replace by putting it after the " in the input statement

#
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(","))}, ill have you {choice('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(","))}.")

removed the replace

pastel sparrow
#

import choice as c and just use that throughout

humble rune
#

thanks

#
from random import choice as c;print("Press the enter key to generate new ones")
while 1:input(f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(","))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(","))}.")
#

maybe shortened it

#

nope doesnt work

#

bruh it just broke

#

bruh it says unmatched (

#

where

languid hare
#

you used " in both the fstring and the split

prisma flame
#

"."

maiden vine
#

Hey esoteric people

earnest wing
#

Hallo

maiden vine
#

Question for you all, its a bit low level

#

Hello!

#

If I wanted to implement a relationship between classes such as between type and object

#

Such that the object class was built using the type class as its metaclass, but the type class inherited from the object class

#

Would I have to essentially write my own PyObject and PyTypeObject classes? And if I did so, beyond all the nastiness, would it be possible to simple not inherit the base type and object classes at all (i.e. they are not present in mro, super calls, etc)

rugged sparrow
upbeat sonnet
#

why do i do this to myself

#

!e ```py
def get_sum(a,b): return sum([i for i in range(a, b + 1)] if a < b else [i for i in range(b, a + 1)])

print(get_sum(6, 9))```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

30
upbeat sonnet
#

yay

maiden vine
rugged sparrow
humble rune
#

!e

def s(a,b):return sum([i for i in range(a,b+1)]if a<b else[i for i in range(b,a+1)])
print(s(6,9))
#

!e

s=lambda a,b:sum([i for i in range(a,b+1)]if a<b else[i for i in range(b,a+1)])
print(s(6,9))
#

poggers

#

@upbeat sonnet

#

!e

from random import choice as c
hehe=lambda:f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(','))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(','))}."
print(hehe())
#

!e

from random import choice as c
hehe=lambda:f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(','))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(','))}."
for i in range(10):print(hehe())
upbeat sonnet
humble rune
upbeat sonnet
#

and whitespace removal

upbeat sonnet
humble rune
#

delete pycharm

#

bloatware

#

code in punchcards like everyone else

upbeat sonnet
humble rune
#

just use hamming codes to protect against stuff like ripped paper or errors while reading

#

obv

upbeat sonnet
#

pc not working rn i think i overheated it

humble rune
#

dip it in water

#

everyone knows water is the best coolant

upbeat sonnet
#

the caps lock blinking

#

very sad

humble rune
#

put ice on it

#

im gonna go make the creator of python cringe in pain

#

at what i have created

wheat river
night quarryBOT
#

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

30
humble rune
upbeat sonnet
night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

30
upbeat sonnet
#

i didnt that was gonna work

#

but this answer is the optimal one

wheat river
#
s=lambda x,y:(y-x+1)*(x+y)//2

i would use this, this is much faster than generating an iterable and getting the sum

upbeat sonnet
#

!e py print((s:=lambda x,y:(y-x+1)*(x+y)//2)(6,9))

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

30
upbeat sonnet
#

jah jah

#

!e py print((s:=lambda x,y:(y-x+1)*(x+y)//2)(9,6))

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

-15
wheat river
upbeat sonnet
#

jah jah

upbeat sonnet
#

!e py print((s:=lambda a,b:sum(range(a,b+1) if a<b else range(b,a+1)))(9,6))

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

30
wheat river
#

ya that only works for ascending order

upbeat sonnet
#

needs the if condition

wheat river
#
s=lambda x,y:(abs(y-x)+1)*(x+y)//2
#

!e

s=lambda x,y:(abs(y-x)+1)*(x+y)//2
print(s(9,6))
print(s(6,9))
night quarryBOT
#

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

001 | 30
002 | 30
earnest wing
night quarryBOT
#

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

30.0
earnest wing
#

oh oops I was scrolled up

#

same as the other people

wheat river
#

!e

s=lambda a,b:abs(b+1-a)*(a+b)/2
print(s(6,9))
print(s(9,6))
night quarryBOT
#

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

001 | 30.0
002 | 15.0
wheat river
#

thats why we need to abs(b-a)

earnest wing
#

right

#

~- instead of (+1) then?

#

or does that bind too loosely

wheat river
#

its going to do the same thing as +1

earnest wing
#

golf

#

avoid parens

next flame
#

bc func call

upbeat sonnet
#
def to_alternating_case(string): return "".join([i.upper() if i.islower() else i.lower()for i in string])```
wheat river
#

!d str.swapcase

night quarryBOT
#

str.swapcase()```
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that `s.swapcase().swapcase() == s`.
upbeat sonnet
#

jah jah

#

why life have to be so sad

#

and why make a method for something so easy to do

sick hound
#

lol

earnest wing
wheat river
wheat river
earnest wing
#

i^32?

upbeat sonnet
#

its the same length-

wheat river
#

oh

#

got it

#
s=lambda x:''.join(chr(i^32)for i in map(ord,x))

πŸ‘€

earnest wing
#

probably needs a check to only casefold alphabetic chars

wheat river
#

hmm yea

sick hound
#

^?

#

i elevated by 32?

wheat river
#
s=lambda x:''.join(chr(i^32)if 64<i<122else chr(i)for i in map(ord,x))
wheat river
sick hound
#

oh

wheat river
#

imma sleep now

#

have a good day/night

upbeat sonnet
#
def alphabet_position(text): return " ".join([str(ord(i) - 96) for i in text.lower() if i.isalpha()])```
upbeat sonnet
#

just doing codewars katas then sending my weird 1 liner answers

#
def number(lines): return [f"{n + 1}: {i}" for n, i in enumerate(lines)]```
earnest wing
#
s=lambda x:''.join(chr(64<i<122and i^32or i)for i in map(ord,x))
upbeat sonnet
#
def capitals(word): return [*sorted([n for n, i in enumerate(word) if i.isupper()])]```
#

i feel like i have a specific programming style

#

i always feel like im doing the same exact thing

quartz wave
# upbeat sonnet i always feel like im doing the same exact thing

you are

def alphabet_position(text): return " ".join([str(ord(i) - 96) for i in text.lower() if i.isalpha()])
^^^^^^^^^^^^^^^^^^^^^ ^^^^                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named function       one arg                          list comprehension
def number(lines): return [f"{n + 1}: {i}" for n, i in enumerate(lines)]
^^^^^^^^^^ ^^^^^          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named func |||||                   list comprehension
          one arg
def capitals(word): return [*sorted([n for n, i in enumerate(word) if i.isupper()])]
^^^^^^^^^^^^ ^^^^                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named func   ||||                          list comprehension
           one arg
sick hound
#

lol

#

perfect explanation

rapid sparrow
#
def run_coro(coro, loop):
  from asyncio import ensure_future, gather
  from threading import Event
  from asyncio.exceptions import InvalidStateError
  fut = ensure_future(loop.create_task(coro))
  g = gather(fut)
  sentinel = object()
  def getter():
    while True:
      yield sentinel
      try:
        yield g.result()
        break
      except InvalidStateError:
        pass
      try:
        yield g.exception()
        break
      except InvalidStateError:
        pass
  return next(filter(lambda o: o is not sentinel, getter()))
#

imports inside function -- check

#

two-space indent -- check

#

what I am trying to do here is "block" on a coroutine (and actually running it) until the result is set @gritty mesa

#

it appeared to work after some fiddling .. I was surprised

#

coz I was getting those warnings until I did the yield stuff

gritty mesa
#

Interesting

floral meteor
earnest wing
floral meteor
#

what if i = 32?

earnest wing
#

False and 0 or 32 == False or 32 == 32

dark cosmos
#

!e

s=lambda x:''.join(chr(i^(32*(64<i<122)))for i in map(ord,x))
print("Hello`")
print(ord('`'))
night quarryBOT
#

@dark cosmos :white_check_mark: Your eval job has completed with return code 0.

001 | Hello`
002 | 96
dark cosmos
#

uhh

#

oh nvm i'm dumb

#

!e

s=lambda x:''.join(chr(i^(32*(64<i<122)))for i in map(ord,x))
print(s("Hello`"))
print(ord('`'))
night quarryBOT
#

@dark cosmos :white_check_mark: Your eval job has completed with return code 0.

001 | hELLO@
002 | 96
dark cosmos
#

the ` character is a problem

#

a problem no longer

s=lambda x:''.join(chr(i^(32*(64<i<122and i!=96)))for i in map(ord,x))
#

though admittedly it's a bit longer than the previous ones

earnest wing
#

the previous ones don't account for it either

dark cosmos
#

fair enough

rugged sparrow
#

!e py s=str.swapcase print(s("Hello`"))

night quarryBOT
#

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

hELLO`
earnest wing
#

well yeah duh

#

the fun is in the approach

rugged sparrow
#

fair

sick hound
#

Esoteric python has so much math

rugged sparrow
night quarryBOT
#

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

hELLO`
pastel sparrow
#

wondering if there was any side effects if i transform the assignments ```py
a = b = c = d

into ```py
((a := d), (b := a), (c := a))
#

can't think of any

wheat river
vestal solstice
#

usually people make a dictionary {42: 'asterisk', 32: '_'}

#

it looks up every ord, if there's no such key, it stays untranslated

#

indexerror is the same class as look up error

#

looks the same

languid hare
#

specfically on a

wheat river
#

!e

from dis import dis
print('= = =')
dis("a = b = c = d")
print(':= := :=')
dis("(a := d), (b := a), (c := a)")
night quarryBOT
#

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

001 | = = =
002 |   1           0 LOAD_NAME                0 (d)
003 |               2 DUP_TOP
004 |               4 STORE_NAME               1 (a)
005 |               6 DUP_TOP
006 |               8 STORE_NAME               2 (b)
007 |              10 STORE_NAME               3 (c)
008 |              12 LOAD_CONST               0 (None)
009 |              14 RETURN_VALUE
010 | := := :=
011 |   1           0 LOAD_NAME                0 (d)
... (truncated - too many lines)

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

wheat river
#

!timeit

a = b = c = d = 10
night quarryBOT
#

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

5000000 loops, best of 5: 48.8 nsec per loop
wheat river
#

!timeit

((d:=10), (a := d), (b := a), (c := a))
night quarryBOT
#

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

2000000 loops, best of 5: 156 nsec per loop
wheat river
#

hmm im making a tuple in the second one

rugged sparrow
#

!timeit why don't you just do this py (c := (b := (a := (d := 10))))

night quarryBOT
#

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

5000000 loops, best of 5: 58.2 nsec per loop
quartz wave
#

!e ```py
from dis import dis
dis("a = b = c = d = 10")
print()
dis("(c := (b := (a := (d := 10))))")

night quarryBOT
#

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

001 |   1           0 LOAD_CONST               0 (10)
002 |               2 DUP_TOP
003 |               4 STORE_NAME               0 (a)
004 |               6 DUP_TOP
005 |               8 STORE_NAME               1 (b)
006 |              10 DUP_TOP
007 |              12 STORE_NAME               2 (c)
008 |              14 STORE_NAME               3 (d)
009 |              16 LOAD_CONST               1 (None)
010 |              18 RETURN_VALUE
011 | 
... (truncated - too many lines)

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

rugged sparrow
night quarryBOT
#

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

001 |   1           0 LOAD_CONST               0 (10)
002 |               2 DUP_TOP
003 |               4 STORE_NAME               0 (a)
004 |               6 DUP_TOP
005 |               8 STORE_NAME               1 (b)
006 |              10 DUP_TOP
007 |              12 STORE_NAME               2 (c)
008 |              14 STORE_NAME               3 (d)
009 |              16 LOAD_CONST               1 (None)
010 |              18 RETURN_VALUE
011 | 
... (truncated - too many lines)

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

rugged sparrow
#

this generates the same bytecode

pastel sparrow
rugged sparrow
quartz wave
#

!e ```py
from dis import dis
dis("a,b=a[b]={},5")
print()
dis("a[b]=(a:={},b:=5)")

night quarryBOT
#

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

001 |   1           0 BUILD_MAP                0
002 |               2 LOAD_CONST               0 (5)
003 |               4 BUILD_TUPLE              2
004 |               6 DUP_TOP
005 |               8 UNPACK_SEQUENCE          2
006 |              10 STORE_NAME               0 (a)
007 |              12 STORE_NAME               1 (b)
008 |              14 LOAD_NAME                0 (a)
009 |              16 LOAD_NAME                1 (b)
010 |              18 STORE_SUBSCR
011 |              20 LOAD_CONST               1 (None)
... (truncated - too many lines)

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

pastel sparrow
radiant anchor
#
from dataclasses import dataclass

class Tree():
    pass

@dataclass
class Leaf(Tree):
    v: int

@dataclass
class Node(Tree):
    left: Tree
    right: Tree

def lambda_match_wrapper(instance, locals): return type("MatchWrapper", (), {"__getattribute__": (lambda self, __name: type("EqWrapper", (), {"__eq__": (lambda self, __o: eval(__o, None, dict(locals, self=instance)))})() if __name == "_lambda" else instance.__getattribute__(__name))})()

def exists_leaf(tree, test):
    match lambda_match_wrapper(tree, locals()):
        case Leaf(_lambda="test(self.v)") \
            | Node(_lambda=\
                "exists_leaf(self.left, test)" \
                | "exists_leaf(self.right, test)"):
            return True
        case _:
            return False

def has_even_leaf(tree):
    return exists_leaf(tree, lambda n: n % 2 == 0)

print(has_even_leaf(Leaf(0)))
print(has_even_leaf(Node(Leaf(3), Node(Leaf(7), Leaf(6)))))
print(has_even_leaf(Node(Leaf(3), Node(Node(Leaf(5), Leaf(27)), Leaf(3)))))
#

so I created a hack to let match cases support lambdas

#

a cool side-effect is that you can OR together multiple lambda strings with |

quartz wave
#

noice

radiant anchor
#

I kinda want to have my "lambdas" support named arguments, like _lambda=(("v",), "test(v)")

#

but I couldn't get that to work

#

for whatever reason, my __eq__ doesn't get called

radiant anchor
#

update: I'm an idiot

#
def exists_leaf(tree: Tree, test):
    match tree:
        case Leaf(v) if test(v) \
            | Node(left, right) if 
                exists_leaf(left, test)
                or exists_leaf(right, test):
            return True
    return False
upbeat sonnet
#
def better_than_average(class_points, your_points): return sum([*class_points, your_points]) / (len(class_points) + 1) < your_points ```
wheat river
#

whats class_points? list?

earnest wing
#

lambda c,y:sum(c)<y*len(c)

radiant anchor
floral meteor
#

initialisation just needs to detect repeated elements that could match with locals() entries 1 frame out.

#

that is if you don't want all tuple creations to exhibit these side effects.

#

otherwise they're the same semantic operation.

quartz wave
#

replying to this to get documentation on one of my old projects

floral meteor
#

!e I'm feeling particularly evil, so no more smoke and mirrors using annotations I'm making 2+2=5 ```py
from ctypes import*
c_int.from_address(id(4)+24).value = 5

print( 2 + 2 )

night quarryBOT
#

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

5
quartz wave
floral meteor
#

excellent, then the chaos shall reign that much more

pastel sparrow
mortal kestrel
#

Hey hello, how can i let python interpret my variable in a string like

variable1 = "test1"

variable2 = "hello variable1"

but interpret the variable 1
thank you for your help

quartz wave
#

reimplemented ```py

a=lambda:5;a.code = a.code.replace(co_code=b'\x97\0d\1d\1d\1d\1f\4S\0',co_stacksize=3);a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line -1, in <lambda>
SystemError: PUSH() operation resulted in a stack overflow (current stack size 4 is greater than maximum stack size 3) (in opcode LOAD_CONST, in file C:\Users\user\Documents\cpython-main\Python\ceval.c at line 1810)
a=lambda:5;a.code = a.code.replace(co_code=b'\x97\0d\1d\1d\1f\4S\0',co_stacksize=3);a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line -1, in <lambda>
SystemError: POP() operation resulted in a stack underflow (current stack size -1 is less than 0) (in opcode BUILD_TUPLE, in file C:\Users\user\Documents\cpython-main\Python\ceval.c at line 3228)

wheat river
upbeat sonnet
#
def high(x):  return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]```
#

!e ```py
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]

print(high('i have no friends'))```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

friends
upbeat sonnet
#

😎

wheat river
#

!e

def high(x):  return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]

print(high('i have no frie1nds'))
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 1, in high
004 | IndexError: list index out of range
upbeat sonnet
#

why did it not-

#

OHH

#

ic

#

i need to remove the invalid terms from the string

night quarryBOT
#
Missing required argument

code

upbeat sonnet
#

!e ```py
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word.lower() if i.isalpha()]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]

print(high('i have no frie1nds'))```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

frie1nds
upbeat sonnet
#

jes

wheat river
#

πŸ‘

pastel ibex
wheat river
#

been sometime since seen u here, welcome

pastel ibex
#

Yeah i disappear for a good while then come back now and again

quartz wave
#
>>> class A:
...     def __add__(self, y):
...             self._ = 5
...             self.y = y
... 
>>> import ctypes
>>> class PyDictValues(ctypes.Structure):
...     _fields_ = [('values', ctypes.py_object*2)] # specifically *2 to fit our case
... 
>>> a = A();a+7;ctypes.POINTER(PyDictValues).from_address(id(a)-32).contents.values[1] # a.y
7
>>> a = A();a+7;ctypes.POINTER(PyDictValues).from_address(id(a)-32).contents.values[0] # a._
5
``` how to get instance attributes in python
sick hound
rose beacon
quartz wave
rose beacon
#

RIP

wheat river
#


a = A();
a + 7;
ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]

Traceback (most recent call last):
  File "C:\Users\ryuga\AppData\Roaming\Python\Python310\site-packages\IPython\core\interactiveshell.py", line 3251, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-a493d47e36e2>", line 3, in <module>
    ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]
ValueError: PyObject is NULL


a = A();
a + 7;
ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]
Process finished with exit code -1073741819 (0xC0000005)

huh?

quartz wave
wheat river
rugged sparrow
quartz wave
#

only works for Py_TPFLAGS_MANAGED_DICT stuff though

granite flax
#

How do i learn how to do esoteric python

granite flax
quartz wave
#

c_int.from_address(id(integer)+24) is basically getting the first number and making it a c_int object

#

then it's assigned to using .value = 5

#

all positive integers up to 256 (end-inclusive) are required to be cached

#

so anywhere, 4 is now equal to 5

#

and you can't change it back

#

so it sucks

granite flax
#

Wtf

granite flax
#

So 24+24+24 will add up to 3?

quartz wave
granite flax
#

πŸ˜”

quartz wave
#

int.__basicsize__ just means the "header" of the integer structure

granite flax
#

Why do people like doing esoteric python what the fuck

quartz wave
granite flax
#

😭

quartz wave
#

size of those stuff add up to 24

granite flax
#

Okay

quartz wave
granite flax
rigid bone
#

!e `print('ggg')

quartz wave
#

it's impossible to make a number that can go very big without using a "list"

granite flax
#

The more you explain this to me the more my confidence in python plummets

quartz wave
#

you shouldn't really know this if you're just a beginner

granite flax
#

I hope so

quartz wave
#

the first element in the "list" is the equivalent of the actual integer itself if it's small enough

#

so we change that to 5

#

and the 4 becomes 5

granite flax
quartz wave
#

because i'm not sure if you know what that means yet

granite flax
rigid bone
#

!e import os
os.system('calc.exe')

night quarryBOT
#

@rigid bone :warning: Your eval job has completed with return code 0.

[No output]
granite flax
rigid bone
#

!e import os
while True:
os.system('calc.exe')

night quarryBOT
#

@rigid bone :warning: Your eval job timed out or ran out of memory.

[No output]
granite flax
#

!e ```py
print(id(4))

night quarryBOT
#

@granite flax :white_check_mark: Your eval job has completed with return code 0.

139839520358736
rigid bone
#

import os
while True:
os.system('calc.exe')

#

!e import os
while True:
os.system('calc.exe')

night quarryBOT
#

@rigid bone :warning: Your eval job timed out or ran out of memory.

[No output]
rigid bone
#

!e import os
while True:
os.system('calc.exe')

night quarryBOT
#

@rigid bone :warning: Your eval job timed out or ran out of memory.

[No output]
quartz wave
quartz wave
granite flax
#

Where did you learn this

quartz wave
#

real "list" is more like [4]

#

except you can't see it like that

#

unless you use a function i made

granite flax
#

What function

quartz wave
rigid bone
#

!e import os
n = 1
while n > 0:
os.system('calc.exe')
n += 1
print(n)

night quarryBOT
#

@rigid bone :x: Your eval job timed out or ran out of memory.

001 | 2
002 | 3
003 | 4
004 | 5
005 | 6
006 | 7
007 | 8
008 | 9
009 | 10
010 | 11
011 | 12
... (truncated - too many lines)

Full output: too long to upload

quartz wave
granite flax
#

I may need to use the function to understand whatever this is

granite flax
maiden blaze
#

there's no "why", it's just how the object is stored in memory

granite flax
maiden blaze
#

under the hood, a python integer is a C struct instance

#

if you read the C source you'll find what the members of the struct are

#

these members are stored one after the other in memory

#

the first few members are stuff like the refcount, a pointer to the type, etc

#

and then comes the actual data of the number

#

id(4) gives you the address where the struct begins
by adding 24 to the address you skip past the initial members and come to the address where the number begins

granite flax
#

Thanks

granite flax
#

This thing

maiden blaze
#

when you add what is love evaluates to True
we want to change the type of True to be NoMore, instead of bool
remember that all objects store a pointer to their type
id(True) is the id of True, id(True) + 8 is the address of the pointer, and we change this value to point to our NoMore class

#

so when it tries to print True, it looks up __str__ on the NoMore class

#

which returns whatever you want it to

maiden blaze
#

to skip past the first member(s) that we do not care about and to get to the address of the member that is the type pointer

maiden blaze
#

the members before the type pointer take up the first 8 bytes

granite flax
granite flax
#

I really want to understand what the hell is happening

#

But can't

wheat river
#

i would say learning little bit of c should help u understand this stuff, although c is a very large lang so it might take a long time

granite flax
#

πŸ˜”

pastel sparrow
#

i mean, being esoteric isn't just about messing with the internals of python

granite flax
#

Can't do it without understanding what it does or how it does it

pastel sparrow
#

google i guess?

granite flax
#

Google what

pastel sparrow
#

i mean- i don't even understand python internals so i can't really help you here :/

sick hound
finite blaze
#

What exactly?

sick hound
#

to make my big code small

#

and some flex xD

finite blaze
#

so you want to learn golfing

sick hound
sick hound
finite blaze
#

so you want to learn golfing

sick hound
#

ok

#

golfing

#

πŸŒοΈβ€β™‚οΈ

wheat river
#

hello and welcome

sick hound
wheat river
sick hound
#

okay

wheat river
#

we overlook stuff like performance/readability basically all the things that guarantee a job at a company πŸ’€

sick hound
#

..

upbeat sonnet
#

!e ```py
def diamond(n): return '\n'.join(['*' * (i + 1) for i in list(range(n)) + list(reversed(range(n - 2)))]) if n > 0 and n % 2 == 1 else None

print(diamond(5))```

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

001 | *
002 | **
003 | ***
004 | ****
005 | *****
006 | ***
007 | **
008 | *
earnest wing
#

challenge: overcomplicated primality checker

#

is_prime: (int) -> bool

wheat river
#

wait does python store 24 bits + memory to store the datatype?

floral meteor
#

!e ```py
print(int.basicsize) # refcount: uint8, type: uint8 pointer, size: uint8, data: uint8[]
print(str.basicsize) # a lot more stuff

night quarryBOT
#

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

001 | 24
002 | 80
maiden blaze
#

(bytes btw, not bits)

floral meteor
#

I did not pick that up lol

wheat river
wheat river
earnest wing
#

right yeah 6x + 3 Β± 2 is not a multiple of 2 or 3

#

now do the same with 2, 3 and 5

fleet bridge
#

!e

import re
def is_prime(n: int) -> bool:
    return re.match(r'^.?$|^(..+?)\1+$', ' ' * n) is None

assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(6)
assert is_prime(7)
assert not is_prime(8)
assert not is_prime(9)
assert not is_prime(10)
assert is_prime(11)
print('ok!')
night quarryBOT
#

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

ok!
fleet bridge
earnest wing
#

Cute!

celest owl
#

People told me to put this here so ..

#
def Ack(m, n):
   if m==0: return n+1
   if m>0 and n==0: return Ack(m-1, 1)
   if m>0 and n>0: return Ack(m-1, Ack(m, n-1))
v0 = 69420
for i in range(69420):
   v0 = v0 ** v0
for i in range(1, 69421):
   globals()[f"v{i}"] = Ack(globals()[f"v{i-1}"] ** globals()[f"v{i-1}"], globals()[f"v{i-1}"] ** globals()[f"v{i-1}"])


while True:
   input()
   v69420 = v69420 - 1
   print(v69420)
   if v69420 == 0:
      print('gg')
      exit()β€Š

dark cosmos
celest owl
#

(funfact, it's my actual code)

finite blaze
#

"assert"

#

I didnt know that something like that existed

prisma coral
sick hound
#

Not sure where the python help channel is so here I am. That's what happens when your server has a billion channels and most with weird names.

sick hound
#

Makes no sense.

granite flax
sick hound
#

Most of the channels make no sense.

#

I've been here before and no one has ever helped. Smaller servers are more useful.

granite flax
#

this channel makes less sense

granite flax
#

just claim a help channel and wait there

sick hound
sick hound
granite flax
#

just post your error in one of the available help channels

sick hound
granite flax
#

and don't leave that channel or just memorize the name

sick hound
#

Give me a # to post my error in.

granite flax
sick hound
#

Duh.

granite flax
sick hound
#

Did. Make no sense.

sick hound
granite flax
wheat river
granite flax
pastel sparrow
wheat river
upbeat sonnet
#

is there a practical use to xor

upbeat sonnet
#

i would not have the patience

quartz wave
# pastel sparrow wait wha- how does this work

if you match nothing, it's not a prime
if you match one character, it's not a prime
if you match a number of characters that are divisible by anything other than itself and 1, it's not a prime

granite flax
quartz wave
# quartz wave if you match nothing, it's not a prime if you match one character, it's not a pr...

how ^(..+?)\1+$ works is that you take this capture group ((..+?)) that matches ONLY when needed
(..+?) basically matches any character then matches anything else only when needed (but it is required)
\1+ repeats the capture group match until it can't
if $ doesn't match, the regex thing tries again with more numbers of characters to match with the capture group because the capture group matches only when needed
then \1+ is tried again
and so on

#

@fleet bridge i somehow figured this out

granite flax
quartz wave
finite blaze
finite blaze
granite flax
quartz wave
humble rune
#

I thought i had tinnitus but no

#

My school is using a mosquito speaker

wheat river
#

"mosquito speaker" ?

quartz wave
#

kind of annoying to hear

#

YouTube's stupid compression takes out anything above 16 kHz, so if you are hearing nothing at all, change the video quality to 720p.

===PLEASE READ DESCRIPTION===

Welcome, welcome, welcome to the home of the most comprehensive collection of beeps, rumbles, chirps and noise on teh Internets!

Although this channel has very many sine wave frequ...

β–Ά Play video
wheat river
#

oh

quartz wave
#

i mean that's what i think is the sound based on the experience that they thought they had tinnitus

wheat river
#

a similar sound comes from one of my stoves

#

its very annoying

upbeat sonnet
upbeat sonnet
tawny carbon
#
@bot.command()
async def coro():
    ...

How do I convert this to a one liner?

royal whale
#

coro = bot.command(lambda: ...)

steady lily
#

pylance doesnt like my expression

languid hare
#

can't imagine why

pastel sparrow
#

looks perfectly fine to me

humble rune
#

i maybe "found" a new tech for removing characters in strings golfed

#

nevermind its slightly larger in most cases unless you have to do it for a lot of characters (like me)

#

its using "string".translate({(UNICODE FOR A CHARACTER):None})

#

shortened my string obfuscator by a bunch though

#

maybe like 20 some characters

#
from random import choices as z
import string as s
a=s.ascii_letters+s.digits+s.punctuation+" "
a,s,n,o=list(a.translate({92:None,39:None,34:None})),input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(s)):o+=s[i]+"".join(z(a,k=n))
print("'%s'[::%i]"%(o,n+1))
#

i gtg

restive void
restive void
#

Golfed a little bit further:

from string import*
s,n,o=input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(s)):o+=s[i]+"".join(__import__("random").choices([*set(ascii_letters+digits+punctuation+" ")-{*"'\"\\"}],k=n))
print("'%s'[::%i]"%(o,n+1))
#

Oh, you save lots by not writing C :P

from string import*
s,n,o=input("String to obfuscate: "),int(input("Split number: ")),""
for i in s:o+=i+"".join(__import__("random").choices([*set(ascii_letters+digits+punctuation+" ")-{*"'\"\\"}],k=n))
print("'%s'[::%i]"%(o,n+1))
severe canyon
#

No need to do the random import inline

restive void
#

Crazy, making it more idiomatic actually shrinks the size for once

restive void
lethal cradle
#

golfed list cloning function i made in like 3 minutes

c = lambda l : [i if type(i)!=type([]) else c(i) for i in l]
#

i dont even know why i did this python already has a method for cloning lists

restive void
severe canyon
#

It's one char shorter

lethal cradle
#

(i removed spaces!)

severe canyon
lethal cradle
#

πŸ’€

#

OH that thing with the * symbol i. Get it now its like

#

because its * in the duplicating item stuff way and. the

restive void
#

Doesn't work with custom objects

lethal cradle
#

so like if you do print("string"*True) then True is 1 so itll print "string" once and if its false itll print it 0 times and. The empty string/list is false so itll

#

wow why am i only just figuring this out

restive void
#

!e

L = [..., 23, 42]
c=lambda l:[i if type(i)!=type([])else c(i)for i in l]
print(c(L))

c=lambda l:[i*(type(i)!=list)or c(i)for i in l]
print(c(L))
night quarryBOT
#

@restive void :x: Your eval job has completed with return code 1.

001 | [Ellipsis, 23, 42]
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 |   File "<string>", line 5, in <lambda>
005 |   File "<string>", line 5, in <listcomp>
006 | TypeError: unsupported operand type(s) for *: 'ellipsis' and 'bool'
restive void
severe canyon
humble rune
#

python code golfing has truly advanced

#

it is kinda sad though that we cant mix whitespace and tabs anymore

severe canyon
sick hound
#

!e ```py
m = getpass.getpass(prompt='hi')
print(m)

night quarryBOT
#

@sick hound :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 'getpass' is not defined
wheat river
#
[*set(__import__('string').printable)-{*"'\"\\\r\n\n"}]

can also use this

quartz wave
#

things out of context

wheat river
#

πŸ˜…

quartz wave
#
[*{*__import__('string').printable}-{*"'\"\\\r\n"}]
wheat river
#

ah yes

#

is there a difference between := and :> in fstrings

quartz wave
#

!e ```py
print(f"{5:=}", f"{5:>}")

night quarryBOT
#

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

5 5
pastel ibex
quartz wave
#

!e ```py
print(f"a{5:=7}a")

night quarryBOT
#

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

a      5a
quartz wave
#

???

wheat river
#

also := doesn't work on strings

#

!e

print(f"""\
{1 :=10}
{'a' :>10}
""")
night quarryBOT
#

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

001 |          1
002 |          a
pastel ibex
#

ah nvm i assumed it was = that centered

wheat river
#

^ is

pastel ibex
#

ah yeah thats right i was right about > tho

wheat river
#

we dont even need the [:] if we are going to type cast it

#
c=lambda l:[eval(str(i))for i in l]
pastel ibex
#

why the eval?

wheat river
#

im dumb we can just do eval(str(l))

wheat river
pastel ibex
#

ah

golden finch
#

g'day, esoteric python people

#

this is probably the right place to put it since my program as a whole is esoteric

#
class Foo:
  def call_on_subclass_creation(self,*subclass_stuff):
    print(subclass_stuff)

class Bar(Foo):0

how could I achieve something along these lines?

#

I could use metaclasses

wheat river
#

maybe use __built_class__

#

but a metaclass would be better

#

*build not built

golden finch
#

yeah, build_class isn't actually properly documented

#

I fiddled with it a few months back

#

the reference implementation doesn't work

#

see this

#

but most importantly, this

golden finch
quartz wave
#

did you try it yet

earnest wing
#

what do you want the output to be

floral meteor
#

Is it bad that I'm using python instead of photoshop/mspaint?

royal whale
wheat river
#

they are going to have diff ids, tho, the goal i belive is to create a copy of the list but [:] doesn't create a copy of a potential sub list

rugged sparrow
#

Why not just list.copy()?

royal whale
upbeat sonnet
#

guys

#

what does var1 = var2 = var3 mean

#

like

#

!e py var1 = var2 = True print(var1, '\n', var2)

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

001 | True 
002 |  True
upbeat sonnet
#

oh

tribal moon
#

ctypes easter egg

#

!e py import ctypes useless_pointer = ctypes.POINTER(ctypes.c_void_p) ctypes.SetPointerType(ctypes.POINTER(ctypes.c_int), useless_pointer)

night quarryBOT
#

@tribal moon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "/usr/local/lib/python3.10/ctypes/__init__.py", line 307, in SetPointerType
004 |     raise RuntimeError("What's this???")
005 | RuntimeError: What's this???
quartz wave
#

!e ```py
import ctypes
ctypes.SetPointerType(3, 6)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "/usr/local/lib/python3.10/ctypes/__init__.py", line 307, in SetPointerType
004 |     raise RuntimeError("What's this???")
005 | RuntimeError: What's this???
wheat river
#

πŸ‘€

#

its serious when the devs had to write a message saying What's this with 3 question marks

quartz wave
#

@ctypes_devs why?

wheat river
#
getattr((bot:=getattr(__import__("importlib").import_module("discord.ext.commands"),'Bot')(command_prefix='^',intents=getattr(__import__('discord'),'Intents').all())), 'command')(name='quack')(lambda ctx:(await ctx.send('quack')for _ in '_').__anext__())

so i made this which is equivalent to

from discord.ext import commands
import discord
bot = commands.Bot(prefix'^', intents=discord.Intents.all())
@bot.command(name='quack')
async def _quack(ctx):
    await ctx.send('quack')

but the thing is in commands.command's init there is this check

        if not asyncio.iscoroutinefunction(func):
            raise TypeError('Callback must be a coroutine.')

how do i bypass that?

quartz wave
#

it's deprecated though

cloud fossil
fiery niche
#

oof

wheat river
#

isn't manually using __anext__() a generator based coro?

upbeat sonnet
floral meteor
#

I have a python script to print matrix rain, which I screenshot and save to an assets folder, then run a script which uses it to generate a desktop background using several other existing assets.

unreal echo
#

here is a guessing game on one line

#
(lambda x, holder1=0: [(lambda guess: (lambda: print('Too high!') if guess > x else (lambda: print('Too low!') if guess < x else (holder1:=1, print('Correct!'), __import__('sys').exit()))())()if i!=10 else (lambda: (holder1:=1) if holder1==1 else print(f'Sorry, the correct answer was {x}.'))())(int(input('Guess a number!: '))) if holder1!=1 else holder1 for i in range(1, 11)])(__import__('random').randint(1, 101))```
unreal echo
#

gotta overwrite the file it's in now

golden finch
#

My mental state has deteriorated sufficiently to return to this channel

golden finch
#
class ModuleUtils:
    hooks={}
    modules={}
    class Hook:
        def __init__(self,hookf):
            self.hookf=hookf
    class OnMessageHook(Hook):
        pass
    class OnReadyHook(Hook):
        pass
    class OnTypingHook(Hook):
        pass
    def load_optional_modules(*modules):
        output('Loading optional modules\n')
        for module in modules:
            ModuleUtils.modules[module.__name__]=module
            output(f'  Loading {module.__name__}\n')
            if hasattr(module,'service'):
                output(f'    Spawning service\n')
                module.service.start()
                output(f'      Spawned service\n')
                @lambda c:c(module)
                class service_respawner:
                    def __init__(self,module):
                        self.module=module
                        self.respawner.start()
                    @tasks.loop(seconds=5)
                    async def respawner(self):
                        if not self.module.service.is_running():
                            self.module.service.start()
                            print(f'restarted {self.module.__name__} service at {datetime.datetime.today().strftime("%d/%m/%Y, %H:%M:%S")}')
                output(f'      Spawned respawner\n')
            for attr in dir(module):
                if issubclass(type(getattr(module,attr)),ModuleUtils.Hook):
                    output(f'    Hooked method {getattr(module,attr).hookf.__name__} to event {type(getattr(module,attr)).__name__}\n')
                    if type(getattr(module,attr)) in ModuleUtils.hooks:
                        ModuleUtils.hooks[type(getattr(module,attr))].append(getattr(module,attr).hookf)
                    else:
                        ModuleUtils.hooks[type(getattr(module,attr))]=[getattr(module,attr).hookf]
        output('\n')
    handle_hooks=lambda event,*arguments:[hook(*arguments)for hook in ModuleUtils.hooks[event]]if event in ModuleUtils.hooks else[]
wheat river
long hamlet
unreal echo
#

just u ig

granite flax
unreal echo
#

and i love how the mods didn't put a cooldown for this channel

golden finch
#

we'd probably just end up making webhooks or something

granite flax
# unreal echo and i love how the mods didn't put a cooldown for this channel
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <listcomp>
  File "<string>", line 1, in <lambda>
  File "<string>", line 1, in <lambda>
UnboundLocalError: local variable 'holder1' referenced before assignment
golden finch
granite flax
#

See what

unreal echo
#

see the error myself

unreal echo
golden finch
#

improves my code

unreal echo
#

yeah i get that error too

#

lemme fix

golden finch
#

leads to abominations like this

unreal echo
#

here ya go py (lambda x: [(lambda guess: (lambda: print('Too high!') if guess > x else (lambda: print('Too low!') if guess < x else (print('Correct!'), __import__('sys').exit()))())()if i!=10 else print(f'Sorry, the correct answer was {x}.'))(int(input('Guess a number!: '))) for i in range(1, 11)])(__import__('random').randint(1, 101))

#

fixed

languid hare
#

more for us :p

unreal echo
golden finch
#

this channel attracts a specific kind of person

unreal echo
#

it's so quiet and peaceful

#

like a, sunset on a beach, just the waves, except online

golden finch
#

the newbs occasionally popping in here to ask for help don't know what hits them

unreal echo
#

lol

languid hare
#

kinda weird how often that happens

golden finch
#

they seem to pick this channel more often than most

unreal echo
#

#bot-commands

golden finch
#

just as I was saying

sick hound
#

my bad

unreal echo
#

you want to unzip it

#

!e print(*map(lambda x: ord(x), 'hello'))

night quarryBOT
#

@unreal echo :white_check_mark: Your eval job has completed with return code 0.

104 101 108 108 111
sick hound
#

yes thank you

#

i forgot what the set() alternative was

golden finch
#

I find this place leaks into my code even when I try to keep it out

vestal solstice
#

!e print(*'hello'.encode())

night quarryBOT
#

@vestal solstice :white_check_mark: Your eval job has completed with return code 0.

104 101 108 108 111
unreal echo
wheat river
unreal echo
quartz wave
floral meteor
#

I just found multiprocessing in python and core affinity in task manager.

#

now I can use all of my cpu to torture python

covert rivet
#

How do you guys have the patience to learn this stuff haha

#

Do you mind explaining this a tiny bit? I have no clue how this works but is it like setting the address to the value True to the value baby don't hurt me?

granite flax
#

Really fucks your brain

edgy kelp
#

the type of the object is stored (or was stored in the version I did it in) at an offset of 8 from its start, then it just replaces the bool type with the NoMore type so when it searches for the str method it finds the custom one instead of bool's

covert rivet
edgy kelp
covert rivet
quartz wave
#

improved ```py

from ctypes import py_object
class NoMore:
... def repr(self):
... return "baby don't hurt me"
...
py_object.from_address(id(True)+tuple.itemsize).value = NoMore
what = love = object()
what is love
baby don't hurt me

#

probably works in 32-bit systems now

#

!e double improved ```py
import('ctypes').py_object.from_address(id(True)+tuple.itemsize).value=what=love=globals()[print(what is love)]=type('',(int,),{'new':lambda _:super().new(1),'str':lambda _:"baby don't hurt me"})

night quarryBOT
#

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

baby don't hurt me
humble rune
# golden finch nope, relapse

me when i relapse into python coding normally with readable code (bad): 😒
my when i make an abomination of unreadable code to save 21 characters: lemon_happy

covert rivet
night quarryBOT
#

Hey @magic wraith!

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

quartz wave
quartz wave
#

fixed

split salmon
#

!e import pickle; print(pickle.loads(b'\x80\x04\x95,\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x07getattr\x94\x93\x94J,\x0f\x01\x00\x8c\x08__hash__\x94\x86\x94R\x94.')())

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

69420
golden finch
#

Why does type.__call__ when used as a class decorator create a new instance of that class?

quartz wave
golden finch
#

mhm

#

I got that far

#

Well, why is ClassExample.__new__ the same as type.__call__(ClassExample)? What's going on in there?

quartz wave
#

gonna have to search the internals for that

#

@golden finch it searches for __new__, errors if it can't find it, else calls it, returns the object if it isn't an instance of the class, else searches for __init__ and calls it if it finds it

golden finch
#

good lord

golden finch
quartz wave
#

roughly equivalent to this (only including the highlighted code) ```py
def type_call(cls, *args, **kwargs):
if cls.new is None:
raise TypeError(f"cannot create '{cls.name}' instances")
obj = cls.new(*args, **kwargs)
if not isinstance(obj, cls):
return obj
if cls.init is not None:
cls.init(obj, *args, **kwargs)
return obj

royal coral
#

Is it possible for us to change the objects in our favor? example: making a new bool (useless, but it's my only idea in mind).

carmine sun
#

but

#

but

#

i reccomend using dunder methods instead

#

unless you just want to add a few things

floral meteor
quartz wave
#

ok

floral meteor
#

Very esoteric use for python, right?

primal idol
quartz wave
pastel sparrow
#

makes sense though

earnest wing
#

Where is that check performed?

covert rivet
#

What’s the error?

pastel sparrow
covert rivet
#

Ah

pastel sparrow
#

yep

covert rivet
#

Ig the only part you inherit would be a __bool__

#

Goddamn thag was hard to do on mobile

pastel sparrow
#

imagine though ```py
class true(bool):
def bool(self):
return False

print(true() is True) # this line is kinda cursed

night quarryBOT
#

Objects/boolobject.c lines 99 to 104

PyDoc_STRVAR(bool_doc,
"bool(x) -> bool\n\
\n\
Returns True when the argument x is true, False otherwise.\n\
The builtins True and False are the only two instances of the class bool.\n\
The class bool is a subclass of the class int, and cannot be subclassed.");```
astral rover
primal idol
#

If bool returned True when instantiated it would be true since they are singletons

#

"singletons"

#

bool is a doubleton xD

pastel sparrow
#

instantiating a bool is cursed

primal idol
#

I mean, it is as cursed as instantiating int I guess

pastel sparrow
#

fair enough

wheat river
night quarryBOT
#

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

True
pastel sparrow
#

damn i did not need to know that it was possible

wheat river
#

!e

from ctypes import py_object

@lambda _: _()
class true:
    def __new__(self):
        return False
    
class trueOrIsIt:
    def __repr__(self):
        return 'true'
py_object.from_address(id(True)+tuple.__itemsize__).value = trueOrIsIt

print(true is False)

i saw this in this channel the other day

night quarryBOT
#

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

true
night quarryBOT
#

Objects/typeobject.c lines 2201 to 2205

if (!_PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
    PyErr_Format(PyExc_TypeError,
                 "type '%.100s' is not an acceptable base type",
                 base_i->tp_name);
    return NULL;```
primal idol
humble rune
cerulean rivet
quartz wave