#esoteric-python

1 messages · Page 58 of 1

whole kiln
#

the rest of it is basically a named capture group, a positive lookahead, and a backreference

#

though apparently I can do a backreference without using a named capture group 🤷🏻

#

and I can specify more than one thing in the lookahead of course

#

didnt think of that

#

(\d)(?=\d\1)

charred steeple
#
'''
124 0 0 100 1    00      22 12 114 30 0     124 0 0 100
02               00                22              12
114 30 0         100              03              00
71               72             110             41
00               124           00              00
100              01          00               22
115              48        00               100
04               00       71 72 110 23     0 124 0 0 100

2 0 22 115        66           00    100 5 0 71 72     110 5 0 124 0
00        71      72          100             00                00
83 4 7 24         24           00            19               24
24        00      24           34          23               65
26        12      76           74        127             147
62 2 54 85         22 76 102 105      122 122 98       117 122 122 9
'''

_ = lambda __, ___: str(bytearray([int(_) for _ in __doc__.split()][__:-___]))
_.__code__ = type(_.__code__)(1, 1, 2, 67, _(0, 1), (None, 3, 5, _(-9, 1),
    _(-9, 5), _(-5, 1)), (), ('',), '', '', 0, '', (), ())
for __ in range(1, 100): _(__)
brisk zenith
#

oh interesting how you put the bytecode in the docstring like that. that's some really nifty stuff right there :D

#

to keep the ints in the docstring a consistent width, you could do hex codes, i.e 0x7c for 124.

sick hound
#

yeah but wouldnt that mess up the int(_) call?

brisk zenith
#

nope

sick hound
#

he would have to do int(_, 16) right

brisk zenith
#

nope

#

when i was editing the cpython source for my custom builtin, i noticed that int(...) is fine with it if you prefix it with 0x

#

oh huh

#

maybe it isn't

#

i swear it is

#

wait 👀

sick hound
#

yeah

#

by default it will try to convert it to base 10

#

you can have a 0x7c literal tho

brisk zenith
#

oh, maybe i was thinking of the actual parser there

sick hound
#
>>> 0x7c
124```
brisk zenith
#

i swear part of the cpython source actually checks for a prefix first

#

i'm not sure though

#

lemme take a look

#
/* Convert an int object to a string, using a given conversion base,
   which should be one of 2, 8 or 16.  Return a string object.
   If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
   if alternate is nonzero. */

static int
long_format_binary(PyObject *aa, int base, int alternate,
                   PyObject **p_output, _PyUnicodeWriter *writer,
                   _PyBytesWriter *bytes_writer, char **bytes_str)
{
    ...
}

ah okay, maybe i was thinking of this

sick hound
#

yeah thats referring to

#

oct() bin() hex()

#

maybe

brisk zenith
#

it is

brisk zenith
#
        self.cells: List[List[Optional[Tile]]] = [
            [None for _ in range(size)] for _ in range(size)
        ]

help

buoyant agate
#
self.cells: List[List[Optional[Tile]]] = [[None] * size for _ in range(size)]```
brisk zenith
#

i feel like that's sorta inconsistent

#

one list is generated with *, one is generated with a listcomp

buoyant agate
#

* is actually faster in this case, and shorter

brisk zenith
#

i'm more concerned about readability.

buoyant agate
#

But yea, I can understand why you'd want the double list comp

brisk zenith
#

resorted to this```py
TileGrid = List[List[Optional[Tile]]]

...

self.cells: TileGrid = [
[None for _ in range(size)] for _ in range(size)
]

viral hedge
#

That is.. quite the typehinting with defaults

buoyant agate
#

Right, forgot about type defs

wind maple
#

use type aliases

brisk bloom
#

The following question is not python based but a general issue I'm facing with github. I'm searched high and low for answers but couldnt find one. If anyone happens to know the answer to it, please let me know why this might be happening. I'd really appreciate it.

#

Here it goes - I'm having a weird issue with my profile not showing up on the insights page on github contributors list. I recently joined the companay and the guy who joined after me which has code which got committed shown in there.

unique shoal
#

this belongs in an off topic channel

brisk bloom
#

@unique shoal I gotcha

#

Is there one here @unique shoal ?

#

cause I can't seem to find any

unique shoal
#

there are several under the off-topic category

brisk bloom
#

oh sorry about that

#

I was confused between channels and sub-headings

#

thanks

unique shoal
#

👍

sterile edge
#
Executing <Task pending coro=<BaseSelectorEventLoop.sock_connect() running at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/selector_events.py:450> wait_for=<Future pending cb=[BaseSelectorEventLoop._sock_connect_done(9)(), <TaskWakeupMethWrapper object at 0xb5fd8350>()] created at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:276> cb=[_run_until_complete_cb() at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:177] created at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:447> took 0.106 seconds
Executing <Task pending coro=<BaseSelectorEventLoop.sock_connect() running at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/selector_events.py:450> wait_for=<Future pending cb=[BaseSelectorEventLoop._sock_connect_done(9)(), <TaskWakeupMethWrapper object at 0xb3598570>()] created at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:276> cb=[_run_until_complete_cb() at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:177] created at /tmp/python-build.20180815000420.1960/Python-3.6.5/Lib/asyncio/base_events.py:447> took 0.105 seconds```
#

what does it mean

unique shoal
#

looks like a log

#

of execution times

#

\o/

sterile edge
#

its executing

#

cuz there was something like this
0:12:11 load avg: 1.19 [ 17/406] test_abstract_numbers

unique shoal
#

benchmarking coroutines?

sterile edge
#

o_o

crimson pumice
#

Can i ask about .sh files here.

wind maple
#

Try an offtopic channel

#

The purpose of this channel is in the description

crimson pumice
#

Hmm.Sorry, this seemed like a off-topic

wind maple
#

offtopic channels are under the offtopic group

crimson pumice
#

ah

#

I just got confused by the weird name

viral hedge
#

Does this quality as barely? ```py
from discord.ext import commands
class Wtf:
def init(self, bot): self.bot=bot
async def on_message(self,msg): await msg.channel.send("Howdy!") if msg.content.startswith("?!hey") else None
class Wtf1:
def init(self, bot): self.bot=bot
async def on_message(self,msg): await msg.channel.send("Howdy!") if msg.content.startswith("?!hi") else None
class Wtf2:
def init(self, bot): self.bot=bot
async def on_message(self,msg): await msg.channel.send("Howdy!") if msg.content.startswith("?!hello") else None
class Wtf3:
def init(self, bot): self.bot=bot
async def on_message(self,msg): await msg.channel.send("Howdy!") if msg.content.startswith("?!howdy") else None
class Wtf4:
def init(self, bot): self.bot=bot
async def on_message(self,msg): await msg.channel.send("Howdy!") if msg.content.startswith("?!sup") else None
def setup(bot): bot.add_cog(Wtf(bot)); bot.add_cog(Wtf1(bot)); bot.add_cog(Wtf2(bot)); bot.add_cog(Wtf3(bot)); bot.add_cog(Wtf4(bot))

#-----------bot.py-------------
import discord
from discord.ext.commands import Bot

bot = Bot(command_prefix="?!")
bot.load_extension("commands")
bot.run("sandwhichmanwhich-rimjob")```

novel vine
#

yes

viral hedge
#

I made my own command system weSmart

unique shoal
#

:c

tepid glacier
#

aaaaaaaaaaaa

crisp pendant
#
def remove_label(self, name):
    self.__applyall(
        lambda label, name=name: (
            lambda label: self.labels.pop(self.labels.index(label)))(label) if label.cget('text') == name else None
    )
#

I regret nothing

arctic bridge
#

What in the name of Mormonism is that

crisp pendant
#

😩

unique shoal
#

@arctic bridge wuh

arctic bridge
#

Huh

#

Sorry lol

tardy kindle
#

I don't even want to try to understand what that does

buoyant agate
#

I think you could remove the outer lambda

def remove_label(self, name):
    self.__applyall(
        lambda label: self.labels.pop(self.labels.index(label)) if label.cget('text') == name else None
    )```
brisk zenith
#
>>> """t""""""h""""""i""""""s""" == "this"
True
>>> 
sick hound
#
>>> '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' == ''
True
>>>```
cunning wave
#
>>> ''''''''''"'''''''''' == ''''"'''
'\'" == "'
>>>
sick hound
#
>>> len('"))'";print("'hello, world"'")"';s=%s'"%"'hello"'";exit(")
42
>>>```
#

(syntax highlighting intentionally not used to make it weirder)

unique shoal
#
>>> len('"))'";print("'hello, world"'")"';s=%s'"%"'hello"'";exit(")
42
>>>```
tropic gulch
#

resistance to syntax highlighting is futile

sick hound
#
>>> eval('''len('"))'";print("'hello, world"'")"';s=%s'"%"'hello"'";exit(")''')
42
>>> ```
pure dew
#

wat

#

that definitely fits "code gore"

atomic violet
#

does anyone know if bashrc/zshrc are executed when user logs into the session via graphical login screen (as opposed to logging into console and typing xinit)?

brisk zenith
#

that's not a question for #esoteric-python (read the channel topic!), but those scripts are executed once a shell session has been started. that means they're executed when logging in on a tty, opening a terminal window, etc.

atomic violet
#

I mean it should be run through shell after login sure but will the interactive rc's (opposed to profile/zlogin) be executed when you are never brought to prompt on startup?

tropic gulch
#

bashrc is for interactive non-login shells only

#

.profile (or .bash_profile or .bash_login) is read for login shells

brisk zenith
#

oh right okay ^-^

tropic gulch
#

it's written as comment at the top of each of those files by default, at least on Ubuntu

tepid glacier
#

Ye

#

The .bash_profile equivalent for Z shell is .zshenv

#

Or is it .zlogin

#

One of those

#

.zshenv is always sourced, then .zprofile is sourced if it's a login shell, then .zshrc is sourced if it's interactive, then .zlogin is sourced if it's a login shell

sick hound
#

´´´r = float(input('Quantos reais você tem na carteira? R$'))
d = r/3,91
print('Com R${:.2f} você pode comprar U${:.2f}'.format(r, d))
´´´

#
d = r/3,91
print('Com R${:.2f} você pode comprar U${:.2f}'.format(r, d))
#

Why isn't it working?

tepid glacier
#

If you're looking for Python help, ask in one of the help channels

sick hound
#

Ok

brisk zenith
#

@quartz zodiac (moving to here) if you run it through python it won't scream about SyntaxErrors (just other errors, which the bytecode modifications fix :D)

quartz zodiac
#

Your thing?

brisk zenith
#

yep

quartz zodiac
#

Maybe I could "fix" the syntax errors... GWgoaThinken

brisk zenith
#

you'd have to delve into the cpython implementation for that.

#

which would be possible, but far from easy.

quartz zodiac
#

It's a nice project for a rainy day.

brisk zenith
#

sure. would be difficult to distribute to other people though, as you'd essentially be making your own version of python itself at that point.

quartz zodiac
#

Naaaahhh, I'll do whatever I can to not do that.

sacred shuttle
#

i need help

quartz zodiac
#

And why's the channel called "barely Python" the place to ask for help, @sacred shuttle?

sacred shuttle
#

idek

sick hound
quartz zodiac
#

Rather than, you know, the 6 channels called "help"...

sacred shuttle
#

well nobody help me in the oothers

cunning wave
#

You have to wait for helo

#

Help

brisk zenith
#

just be patient.

#

asking in multiple places is only going to make people annoyed c:

quartz zodiac
#

You waited not even a minute before asking a second time.

cunning wave
#

In some forums it might take days or even weeks until you get hrlp

#

So compared to them you'll get help here quite fast

sacred shuttle
#

well okay

atomic violet
#

Anyone else feel frustrated with the white/alabaster theme of Read the Docs (flask, requests, etc.)? Seems like it's been getting somewhat trendy for python projects but I always get lost and struggle to find specific methods/sections in it opposed to the standard blue theme with a sidebar.

brisk zenith
#

i refer to those quite often but i don't typically struggle to make my way through them, but i do certainly prefer the other theme. also, this :D

atomic violet
#

Where would my rant fit then? It's not quite python nor python specific, just "barely python" so it felt perfect here. 😪

brisk zenith
#

i do feel like this channel needs a better name or something, honestly. ¯_(ツ)_/¯

cunning wave
#

The channel name and inability or lazyness of users to read channel descriptions makes this channel miss used quite often

sick hound
#
with switch(value):
    with case(1):
        print('hello')
    with case(2):
        print('hello, again')
    with default:
        print('default')```
cunning wave
#

But but I want breaks

sick hound
#

hmm

brisk zenith
#

you could do that

#

it's not invalid syntax.

sick hound
#
while switch(value):
    with case(1):
        print('hello')
        break
    with case(2):
        print('hello again')
        break
    with default:
        print('hi')
        break```
brisk zenith
#

oh wait, maybe it is.

cunning wave
#

Also youd usually do {} around the switch block

brisk zenith
#

¯_(ツ)_/¯

cunning wave
#

Do one would have to subclass the dictionary

brisk zenith
#

you can't put multiple statements in dictionary keys, that's why it's not possible

sick hound
#

^

cunning wave
#

Hmmmmmmmmmm

pure dew
#

or just

sick hound
#

you can't put any statements in dictionary keys/values

brisk zenith
#

you can put one statement?

#

quite like lambdas.

sick hound
#
>>> {x: y = 1}
  File "<stdin>", line 1
    {x: y = 1}
          ^
SyntaxError: invalid syntax```
brisk zenith
#

oh right.

cunning wave
#

DICTONIARIES WITH DICTIONARIES CONTAINING LISTS OF INSTRUCTIONS

brisk zenith
#

NIX NO

cunning wave
#

Bringing braces to python

#

2.0

brisk zenith
#

IMPORT BRACES

sick hound
#
from __future__ import braces```
pure dew
#

hrm biskthink you may need to modify the parser to make it clean

brisk zenith
#

already been discussed, but it's not really ideal

sick hound
#
switch value:
    case 1:
        print('hello')
        break
    case 2:
        print('hello again')
        break```
brisk zenith
#

at that point you may as well make a PEP and PR it

sick hound
#

if you want something like that then you need to change the parser

brisk zenith
#

yup

cunning wave
#

I changed the parsers before

brisk zenith
#

same here

cunning wave
#

It's fun for 2.7 but

#

3.6 parser changes

#

Ew

brisk zenith
#

yeah

#

it's naff.

cunning wave
#

Like in 2.7 if you're not modifying the elif else grammar everything's just edit the grammar file

#

In 3.6

#

edit grammar file + millions of c files to make one change

sick hound
#
while switch(value):
    if case(1):
        print('hello')
        break
    if case(2):
        print('hello')
        break
    if default:
        print('hello')
        break``` this could be possible without any code-changing magic at all
brisk zenith
#

hmm true

#

switch and case would be easy enough

#

default, maybe not.

sick hound
#

default = True

sacred shuttle
#

T_T

brisk zenith
#
# The default filesystem data when using `mkfs.vfat -F 12`
# from `dosfstools` on a typical 1.44M file/partition/etc.
# Rows of null bytes have been removed for convenience.
_VFAT12_SPARSE_DATA = {

    # The MBR sector at the start of the storage.
    0x000000: """
        3ceb 6d90 666b 2e73 6166 0074 0102 0001
        e002 4000 f00b 0009 0012 0002 0000 0000
        0000 0000 0000 5529 9d4e 4ee8 204f 414e
        454d 2020 2020 4146 3154 2032 2020 1f0e
        5bbe ac7c c022 0b74 b456 bb0e 0007 10cd
        eb5e 32f0 cde4 cd16 eb19 54fe 6968 2073
        7369 6e20 746f 6120 6220 6f6f 6174 6c62
        2065 6964 6b73 202e 5020 656c 7361 2065
        6e69 6573 7472 6120 6220 6f6f 6174 6c62
        2065 6c66 706f 7970 6120 646e 0a0d 7270
        7365 2073 6e61 2079 656b 2079 6f74 7420
        7972 6120 6167 6e69 2e20 2e2e 0d20 000a
        """,

    # MBR signature and something else, not sure.
    0x0001ed: """
        aa55 fff0 00ff 0000 0000 0000 0000 0000
        """,

    # Same as above. Perhaps metadata boundaries?
    0x001400: """
        fff0 00ff 0000 0000 0000 0000 0000 0000
        """,

    # Just some null bytes to truncate at 1.44M
    0x167ff0: """
        0000 0000 0000 0000 0000 0000 0000 0000
        """
}

how's this for code-gore? :^)

sick hound
#
import sys

_f_switches = {}

def _getswitch(frame, exact=False):
    if not frame in _f_switches:
        return None
    result = None
    for s in _f_switches[frame]:
        if exact:
            if s[0] == frame.f_lasti:
                if result is None or result[0] <= s[0]:
                    result = s
        elif s[0] <= frame.f_lasti:
            if result is None or result[0] <= s[0]:
                result = s
    return result

def switch(val):
    frame = sys._getframe(1)
    if not frame in _f_switches:
        _f_switches[frame] = []
    s = _getswitch(frame, exact=True)
    if s:
        raise SyntaxError((s, frame.f_lasti))
    _f_switches[frame].append([frame.f_lasti, val, False])
    return True

def case(val):
    frame = sys._getframe(1)
    s = _getswitch(frame)
    if s is None:
        raise SyntaxError
    elif s[2]:
        return True
    elif s[1] == val:
        s[2] = True
        return True
    return False

default = True```
pure dew
#

yikes

#

thats almost worst than my dash code

sick hound
#
value = 0
while switch(value):
    if case(0):
        print('Zero')
    if case(1):
        print('One')
        break
    if case(2):
        print('Two')
        break
    if default:
        print('Default')
        break

value = 4
while switch(value):
    if case(0):
        print('Zero')
    if case(1):
        print('One')
        break
    if case(2):
        print('Two')
        break
    if default:
        print('Default')
        break

# Output: Zero, One, Default```
brisk zenith
#

nifty

sick hound
#

no decorators

brisk zenith
#

that's what i was thinking

sick hound
#

Beautiful

calm rampart
#
for sw in switch(value):
    if sw.case(1): ...
    if sw.default: ...

default would have to be last though

sick hound
#

that's not weird enough

calm rampart
#

what about just implementing goto, then implementing switch on top of goto

#

use strings for labels

#
def foo():
    some stuff
    "label:"
    some other stuff
    goto("label")```
#
def bar():
    while switch(value):
        "case"(1)
        some stuff
        "case"(2)
        some other stuff
        break```
#

convert switch to a goto that goes to any statement that has "case"(the value) inside the loop

#

the problem with any solution that doesn't modify the parser or modify the bytecode is that the whole set of case values isn't available to check if default should be reached

sick hound
#

look at my solution

calm rampart
#

default = True simply is not good enough

sick hound
#

if any of the cases get triggered and break then it won't even reach the if default:

calm rampart
#
switch(2) {
    default: printf("default\n"); break;
    case 2: printf("case 2\n"); break;
}```
sick hound
#

hmm

#

actually i just realized

#

my solution also won't handle nested switches

light patrol
#

can this serve as a math channel

#

i think it can

sick hound
#

not exactly, but you can discuss math related stuff in an off topic channel

pure dew
#

I'm not sure this totally fits, but it's kinda a VM language, and there isn't a channel for "totally obscure things no one should want to do", so I'll post it here

brisk zenith
#

probably suitable

pure dew
#

Long story short, I'm making a Discord bot with discord.py that takes bash syntax, turns it into an AST (courtesy of bashlex), and then runs commands in python instead of the shell.

The couple design iterations I've had so far don't work too well. Has anyone heard of a project like this, or have anu ideas for actually executing the commands while handling redirection, piping, chaining, conditionals, iterators, etc?

brisk zenith
#

hmm..

pure dew
brisk zenith
#

looks interesting, certainly

#

my only suggestion would be to look at how sh itself works

pure dew
#

Yea I've been reading about piping and redirection

#

My thought was to have a session context that handles chaining and iterators and whatnot and just make a new discord.py context within that for each command

brisk zenith
#

what sort of commands does this bot respond to?

#

gimme an example of something you'd like to have in there

pure dew
#

right now it does sudo, echo, shutdown, sleep, etc

#

some basic shell stuff

#

like echo 55 && sleep 3 ; echo sleep over

#

it does that fine, but its messy, and i kinda locked myself with some design choices

brisk zenith
#

i maybe have an idea, but im not too sure

pure dew
#

I'm trying to emulate sh behavior as best I can, while making easy to use on discord

brisk zenith
#

basically, why not make the bot run the actual commands from a shell in an isolated environment, where the only programs it has access to are ones you write (like, custom scripts for echo and shutdown etc that it runs inside of the isolated env)

#

probably a terrible explanation

pure dew
#

nonono

#

I don't want it to run shell commands

#

its all in discord, but with shell syntax

brisk zenith
#

i cant explain what i mean haha

pure dew
#

I have a command system in place (d.py commands ext)

#

instead of calling shell scripts, it finds a command in that command system and calls it

brisk zenith
#

oh i see

#

well it seems tricky

pure dew
#

my thoughts exactly

willow river
#

Noob question of the day, why I never see anyone being redirected to python official howto ?

unique shoal
willow river
#

Because the noob in the me of today didn't knew what's up with this channel so he tried it

unique shoal
#

it does have a description

willow river
#

aight

#

where should i ask this kind of htings then ?

unique shoal
willow river
#

True true

polar vector
#

!sourced

#

!source

#

!help

night quarryBOT
#
Doc:
  docs        Lookup documentation for Python symbols.
Information:
  server      Returns an embed full of
  user        Returns info about a user.
Reddit:
  reddit      View the top posts from various subreddits.
Site:
  site        Commands for getting info about our website.
Snakes:
  snakes      Commands from our first code jam.
Utils:
  pep         Fetches information about a PEP and sends it to the channel.
​No Category:
  help        Shows this message.

Type !help command for more info on a command.
You can also type !help category for more info on a category.
polar vector
#

!server

night quarryBOT
#

Server information
Created: 1 year, 7 months and 13 days ago
Voice region: vip-amsterdam
Features: VIP_REGIONS, VANITY_URL, INVITE_SPLASH

Counts
Members: 7020
Roles: 21
Text: 65
Voice: 8
Channel categories: 12

Members
status_online 663
status_idle 597
status_dnd 191
status_offline 5569

vague gust
#

Please use commands for the bot in #bot-commands

viral bough
cunning wave
#

thats just a pep8 violation nothing weird

pure dew
#

oof

viral bough
#

which bit violates pep?

pure dew
#

thats not as bad as my f-string ab00s tho

#

i oneline it

cunning wave
#

wait no this is a two liner format string inside a function argument

#

dont do that

brisk zenith
#
>>> __builtins__.__loader__.get_source(__builtins__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 235, in _requires_builtin_wrapper
ImportError: <module 'builtins' (built-in)> is not a built-in module
>>> 

python explain

cunning wave
#

if builtins had a reference to itself it would have to circulary load itself wouldnt it? @brisk zenith

brisk zenith
#

well not really

#

but what other "built-in" module is there?

cunning wave
#

who knows

arctic bridge
#
#    wildfire.py - Self-modifying Python bytecode: w.i.l.d.f.i.r.e
#    Copyright (C) 2013 Axel "0vercl0k" Souchet - http://www.twitter.com/0vercl0k
cunning wave
#

sounds unhealthy

thorny granite
#

@brisk zenith sys is the only other one

sick hound
#

__main__

#
>>> import __main__
>>> __main__
<module '__main__' (built-in)>
>>> ```
#
>>> import __main__
>>> dir(__main__)
['__annotations__', '__builtins__', '__doc__', '__loader__', '__main__', '__name__', '__package__', '__spec__']
>>> x = 5
>>> dir(__main__)
['__annotations__', '__builtins__', '__doc__', '__loader__', '__main__', '__name__', '__package__', '__spec__', 'x']
>>> __main__.x
5
>>> __main__.x = 42
>>> x
42
>>> ```
#

@brisk zenith

thorny granite
#

thats something

#

well it looks like every c module is considered built-in so nvm

#

oh wait no

#

yea builtins and sys are special

sick hound
#
>>> import _socket
>>> _socket
<module '_socket' from 'C:\\Users\\Aaay\\AppData\\Local\\Programs\\Python\\Python36\\DLLs\\_socket.pyd'>```
thorny granite
#

im too confused

brisk zenith
#

_sitebuiltins is a good one too

sick hound
#
>>> xd
Use xd() or xd() to exit```
#
>>> import pydoc
>>> pydoc.help = lambda *args, **kwargs: print('lol')
>>> help()
lol
>>> ```
brisk zenith
#

is that top one _sitebuiltins.Quitter?

#

hmm

#

i wonder if it's somehow possible to capture the return value of exit()

#

i believe exit(n) returns (n,)

#

where n defaults to Noen

#

yes, Noen apparently.

sick hound
#

the top one is _sitebuiltins.Quitter

#

also exit() doesn't return anything, it closes stdin and raises SystemExit

#

why would it return a tuple

#

_io doesn't know what its name is

#
>>> import _io
>>> _io
<module 'io' (built-in)>```
#
>>> import _io
>>> _io
<module 'io' (built-in)>
>>> _io.StringIO
<class '_io.StringIO'>: # extra colon to fix syntax highlighting
>>> _io.StringIO.__module__
'_io'
>>> _io
<module 'io' (built-in)>
>>> _io.__name__
'io'
>>> ```
#
>>> __builtins__.__loader__.get_source(_io)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 235, in _requires_builtin_wrapper
ImportError: <module 'io' (built-in)> is not a built-in module```
#
>>> print
<built-in function print>
>>> del print
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'print' is not defined
>>> ```
brisk zenith
#

haha

sick hound
#
>>> import sys
>>> del sys.modules['__main__']
>>> sys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> __builtins__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__builtins__' is not defined
>>> print
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'print' is not defined
>>> ```
brisk zenith
#

oh damn :D

sick hound
#
>>> import __main__
>>> __main__
<module '__main__'>
>>> ``` (after eventually getting `__builtins__` back)
#

__main__ exists again but it isn't built in anymore

brisk zenith
#

hmm

#

interesting

sick hound
#
>>> import sys
>>> import os
>>> sys
<module 'sys' (built-in)>
>>> os
<module 'os' from 'C:\\Users\\Aaay\\AppData\\Local\\Programs\\Python\\Python36\\lib\\os.py'>
>>> os.__loader__ = sys.__loader__
>>> os
<module 'os' (built-in)>
>>> ```
brisk zenith
#

makes sense

sick hound
#

if you set the __loader__ of a module to the builtin module loader it becomes a "built in" module

brisk zenith
#

yup

sick hound
#
>>> import sys
>>> sys.__loader__ = sys
>>> sys
<module 'sys' (<class '_frozen_importlib.BuiltinImporter'>)>
>>> ```
pure dew
#

lolwat

sick hound
#
# waat.py
__loader__ = __import__('sys').__loader__

>>> import waat
>>> waat
<module 'waat' (built-in)>
>>> ```
pure dew
#

ooh

#

what does the loader do

sick hound
#

load things

pure dew
#

oh, it just defines how to import a module?

sick hound
#

it's complicated

#

but if you set the __loader__ of a module

#

that doesn't change how the module is loaded

#

but it does change how the module thinks it was loaded

#

any module that has a __loader__ of <class '_frozen_importlib.BuiltinImporter'> (like sys) will appear as built in

#
>>> import os, sys
>>> os
<module 'os' from 'C:\\Users\\Aaay\\AppData\\Local\\Programs\\Python\\Python36\\lib\\os.py'>
>>> os.__loader__ = sys.__loader__
>>> os
<module 'os' (built-in)>
>>> ```
pure dew
#

what can you do with a custom loader?

sick hound
#
>>> import hello
>>> hello
42
>>> ``` basically anything
pure dew
#

oof

>>> import discord
>>> import sys
>>> discord.__loader__ = sys.__loader__
>>> __loader__.get_code(discord)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 235, in _requires_builtin_wrapper
ImportError: <module 'discord' (built-in)> is not a built-in module
sick hound
#
>>> import also_also_also_also_also_sys
>>> also_also_also_also_also_sys
<module 'sys' (built-in)>
>>> ```
pure dew
#

lol

sick hound
#
>>> import str_helloworld
>>> str_helloworld
'helloworld'
>>> ```
#
>>> import exit
# (exited)```
pure dew
#

The import path is a list of locations that may name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs.

#

🤔 dynamic module loading?

#

no more pip install?

sick hound
#

maybe

pure dew
#

nah that'd be slow

#

actually

#

if you cache it, maybe not

pine edge
#

pip is pretty fast for a package manager

#

i wouldn't mind a 40 mb download to start an app i rarely use

pure dew
#

i mean download and compiling

#

either there'd have to be a system call to sudo (idk how that'd go over) or we just install the packages locally

pine edge
#

pip has local install indeed

pure dew
#

Yea i know, i install all my packages locally

#

compiling would be the big issue tho

cunning wave
#

so i just opened python and without me doing anything this happened

brisk zenith
#

lmao

tropic gulch
#

intentional name leak?

brisk zenith
#

nah everyone knows nix's name by now

#

it's obviously jesus

tropic gulch
#

I don't remember having seen it ¯_(ツ)_/¯

brisk zenith
#

oh fair.

knotty bronze
#

since this is #esoteric-python how you add a command, or making one in visual studio code? please come with examples

cunning wave
#

this is not related to #esoteric-python which you would know in case you read the channel topics (why do people never read channel topics) if you have questions about a specific tool go to #tools-and-devops

knotty bronze
#

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

sick hound
novel vine
#

@cunning wave if your python did that without you intentionally fucking with it check your HDD health

cunning wave
#

uhm

#

why

novel vine
#

Was just thinking random things like that could be a corruption issue & sectors going bad

cunning wave
#

hm

#

i mean i got linux on that hdd and it can boot perfectly fine

novel vine
#

Probably isn’t but could be shrug

cunning wave
#

welp

#

lets hope it doesnt die after under a year

mystic ether
#

🏌

brisk zenith
#

viral hedge
last bramble
#

4

brisk zenith
#

for

patent sedge
#

Aint nobody talking. sad stuff. 😦

lilac sable
#
#!/usr/bin/python
import re,os,cgi;d,h=os.listdir('.'),'<a href=wy?';p,e,g,s=tuple(map(cgi.parse(
).get,'pegs'));f=lambda s:reduce(lambda s,(r,q):re.sub('(?m)'+r,q,s),(('\r','')
,('([A-Z][a-z]+){2,}',lambda m:('%s'+h+'e=%s>?</a>',h+'g=%s>%s</a>')[m.group(0)
in d]%((m.group(0),)*2)),('^{{$','<ul>'),('^# ','<li>'),('^}}$','</ul>'),('(ht\
tp:[^<>"\s]+)',h[:-3]+r'\1>\1</a>'),('\n\n','<p>')),s);o,g=lambda y:(y in d and
cgi.escape(open(y).read()))or'',(g or p and[open(p[0].strip('./'),'w').write(s[
0])or p[0]]or[0])[0];print'Content-Type:text/html\n\n'+(s and', '.join([f(n)for
n in d if s[0]in o(n)])or'')+(e and'<form action=wy?p=%s method=POST><textarea\
 name=s rows=8 cols=50>%s</textarea><input type=submit></form>'%(e[0],o(e[0]))
or'')+(g and'<h1>%ss=%s>%s</a>,%se=%s>edit</a></h1>'%(h,g,g,h,g)+f(o(g))or'')
#

11 line wiki in Python

dense spire
#

jesus :D

lilac sable
#

yeah

dense spire
#

that's pretty impressive

#

too bad the example doesn't work

lilac sable
#

hm

#

I believe its for Python 2

sick hound
lilac sable
#

okay no errors in Python 2

dense spire
#

no, I mean the example link on that website you linked

#

the code probably works :P

lilac sable
#

oh lol yeah xD

lusty vector
#

Okay. So @unique shoal and @worthy pollen , this is what I was trying to do with hist question and HyperTurtles code-bit:

''.join([str(f'{string.ascii_lowercase} '.index(i)+1) if i !=' ' else ' ' for i in mystring])

Some kind of golfing I guess

worthy pollen
#

you could drop my f-string & not sure how useful the .join and str are...

brisk zenith
#

you can do if not i

worthy pollen
#

or i.isalpha()

pure dew
#

@sick hound that r refers to a raw string, that highlighting is correct

sick hound
#

Must be just very weird placement

pure dew
#

no??

#

it makes sense to me

sick hound
#

look at the letter right before the r and then the character right before that

pure dew
#

Yes, the highlighter just parses the source, it doesnt know the context

tepid glacier
#

So I've written a thing

#
def snail(a):
    o=[]
    while a:
        o+=a.pop(0)+[s.pop()for s in a[:-1]]
        if not a:break
        o+=a.pop()[::-1]+[s.pop(0)for s in a[::-1]]
    return o
#

Is it possible to golf this further?

#

(The only restriction is the function name)

#
def snail(a):
    o=[]
    while a:
        o+=a.pop(0)+[s.pop()for s in a[:-1]]
        if a:o+=a.pop()[::-1]+[s.pop(0)for s in a[::-1]]
    return o
#

changed it up a bit

wind maple
#

what does it do

#

oh like a spiral

tepid glacier
#

yeah

#

clockwise spiral, starting from the first element

brisk zenith
#

looks like codewars to me

wind maple
#

I guess this is cheating but

#
>>> def snail(a):
...     while a:
...         yield from a.pop(0)
...         a = list(zip(*a))[::-1]```
tepid glacier
#

@brisk zenith Yeah, it's a codewars challenge

brisk zenith
#

why not ...+s[::-1] rather than [s.pop(0)for s in a[::-1]]..? i swear they're the same..

#

i'm so tired.. lmao

tepid glacier
#

Submitted it a few minutes ago and saw all these good answers GWseremePeepoLife

brisk zenith
#

oh

#

of course that doesn't work

#

misread

sick hound
#

if it's the question i'm thinking of the top answer blew my damn mind

#

when i saw it

#

hadn't been thinking of it as a recursion problem at all lol

pure dew
#

post a link pls

wind maple
#

oh yeah you could do that recursively

#
>>> def snail(a):
...     return a[0] + snail(list(map(list, zip(*a[1:])))[::-1]) if a else []```
frosty wyvern
#

pythonic hyperlemon

wind maple
#

v

tropic gulch
#

might make it a lambda for further golf

#

also a if x else b can be written as [b,a][x==0]. Depends on the terms and whether whitespace is counted what is shorter

tepid glacier
#

Assuming you're referencing this one

frosty wyvern
#

My eyes are bleeding

tropic gulch
tepid glacier
#

This is still my favourite solution

frosty wyvern
#

I'm so bad at coding challenges, I really need to brush up

wind maple
#

Oh you could have just put the list cast there

#

Damn I'm stupid

sick hound
#

that's it yee
for some reason i hadn't even realized before seeing it that zip is transposition

#

close enough, ava :p also neat turns out you were actually there when i asked about this in tcd forever ago

quick oracle
#

How can I paste formatted code into discord?

tropic gulch
#

!t codeblock

night quarryBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
quick oracle
#

Thanks.

rare juniper
#

@brisk zenith

class OhFuck:
    def __eq__(self, other):
        self = self.__class__()
        return super().__eq__(other)

def thing_is_thing(thing):
    if thing != thing:
        return False
    if thing == thing:
        return True

print(thing_is_thing(OhFuck)) # -> True
print(thing_is_thing(OhFuck())) # -> True
print(thing_is_thing(OhFuck().__eq__('WaitWhatIsOther'))) # -> True
print(thing_is_thing(OhFuck().__eq__(OhFuck()))) # -> True```
#

How exactly did you mean for this to work?

whole kiln
brisk zenith
#

huh, one sec lemme get on my computer

rare juniper
#

@whole kiln Holy fucking SHIT.

brisk zenith
#

yeah that's interpreter optimisation there i think

#

I mean really, you could tell __eq__ to always return False

rare juniper
#

Ohhh... Jesus.

#

I guess you can change your name to...

#

Jaun is still not Juan 😎

brisk zenith
#

:^)

#

but as for is, that cannot be.. hold on, hold my water-flavoured transparent beer

#

prepare yourself for some "what the fuck" code

#

cause i'm writing some

brisk zenith
rare juniper
#

oh my god

brisk zenith
#

if i could be bothered to put more effort into it, i'd make it actually change the value of it after an is operation

rare juniper
#

Is there any way around using a decorator? On that specific function, at least.

brisk zenith
#

not really, other than editing the function directly which works too

#

except all the code would be moved from the decorator function to the global scope

#

but all that code does is change the internal bytecode of the function, so thing is thing just becomes False.

rare juniper
#

where do you even learn this stuff

#

what do you DO

brisk zenith
#

haha

#

i don't 😎

#

the bytecode is changed from this:

  2           0 LOAD_FAST                0 (thing)
              2 LOAD_FAST                0 (thing)
              4 COMPARE_OP               8 (is)
              6 RETURN_VALUE

to this:

  2           0 LOAD_CONST               1 (False)
              2 RETURN_VALUE
#

for the decorated example function, that is

#

but it'll work for any case of thing is thing

#

it's pretty much an internal version of editing the function so that it turns from

def thing_is_thing(thing):
    return thing is thing```
into:
```py
def thing_is_thing(thing):
    return False
#

and stuff like ```py
def thing_is_thing(thing):
if thing is thing:
print("yes hello")

would become
```py
def thing_is_thing(thing):
    if False:
        print("yes hello")
rare juniper
#

if False 😰

brisk zenith
#

but i could change my decorator function so that it turns:

return thing is thing

into

thing = "hello"
return thing
#

so then technically, py thing is thing is thing
would be.. false and true

#

at the same time

#

oh boy

rare juniper
#

quantum computing breakthrough?

brisk zenith
#

nope

#

just idiocy

rare juniper
#

damn!

brisk zenith
#

i mean obviously it wouldn't be False and True at the same time

#

but it'd be fucked, is what i'm saying :D

rare juniper
#

As long as it's fucked that's all that really matters.

brisk zenith
#

or maybe it is quantum mechanics and we introduce a Maybe

rare juniper
#

... This started as me trying to use python code as an analogy in a philosophy essay

#

but I got side-tracked

brisk zenith
#

my life is a side-track honestly

#

ooh

#

i just had a fun idea

#
def fuck(thing):
    other = thing
    
    if thing is not thing:
        return True

    if other is not thing:
        return False

    return True

i could make this return False

#

i think that's right anyways

#

eh, effort lmao

#

i'll work on it if i ever feel bored again :D

muted basin
#

great name

brisk zenith
#

hell yeah

pure dew
#

wheres the place to talk about other-langauge extensions (C, Rust, C++, etc)?

brisk zenith
#

off-topic

#

we used to have a channel for that, but it lives no longer

#

(i think it's archived)

pine lantern
#

Ho together. I have one other question. hope to be in right channel. How can i get with Python3 the newest Video of an Youtube Channel.

unique shoal
#

this is not the right channel for that

#

I am not sure what it is about this channel name that brings everyone here

#

make sure to read channel descriptions please, everyone

pine lantern
#

Sorry then. which channel is right? My english is not so gut and havent know what berely means @unique shoal

unique shoal
#

any of the regular help channels

pine lantern
#

Oh havent seen them. Thanks and sorry for that. Shame on me 😃

willow inlet
#

🏿 🏿 🏿 🏿 🏿 🏿 🏿 🏿
🏿 🏿 🏽 🏽 🏽 🏽 🏿 🏿
🏽 🏽 🏽 🏽 🏽 🏽 🏽 🏽
🏽 ⬜ ⬜ 🏽 🏽 ⬜ ⬜ 🏽
🏽 🏽 🏽 🏽 🏽 🏽 🏽 🏽
🏽 🏽 🏿 🏽 🏽 🏿 🏽 🏽
🏽 🏽 🏿 🏿 🏿 🏿 🏽 🏽
🏽 🏽 🏽 🏽 🏽 🏽 🏽 🏽
Copy and paste on 5 other Discords or else Herobrine will hack your Minecraft account

pure dew
#

-_-

fading fractal
#

Is this chat just for any other language?

sick hound
#

@willow inlet dont shitpost here

#

and @fading fractal not necessarily, read the channel topic

fading fractal
#

oh so, there is no channel for other langs

sick hound
#

nope, feel free to discuss other langs in an offtopic channel though

fading fractal
#

Aight

novel vine
#

This is like code golf / python hackery

pure dew
#

abuse of f-strings?

worthy pollen
#
>>> people = int(input('people: '))
>>> total_slices = int(input('no. of pizzas: '))*8
>>> share, left = divmod(total_slices,people)
>>> f'{people - left} get {share} slices. {left} will get {share +1}'.split(' 0 ')[0]```
#

pizza problem without conditionals

brisk zenith
#

oh nifty

broken agate
#

there's a pizza problem?

novel vine
#

kinda

#

it's like how can people split a pizza given x people y slices

versed ginkgo
#

any good code jams?

sick hound
#

(this one isn't a general off-topic channel! check its description)

feral spade
#

Hello

#

How are you guys

#

😃

#

could someone recommend me some good lambda code samples, I still don't understand its use-case, I know it's good in functional programming, but need a little more to understand it.

frosty wyvern
#

A lambda is pretty much just an inline anonymous function, you can pass it around like a value/regular function

unique shoal
cunning wave
#

It's about squeezing out the last use cases of lambdas

brisk zenith
#

lambda: lambda: ...

sick hound
#

this is for bad lambda code samples

#

(lambda f:f(f))(lambda y:lambda f:lambda:f(y(y)(f)))(lambda f:lambda n:f()(n-1)*n if n else 1)() like this implementation of factorial

frosty wyvern
#

What's wrong with that? It's perfectly readable

sick hound
#

._.

feral spade
#

what's that, Valyrian ?

frosty wyvern
#

It's evidently a factorial function

#

Can you even read ? scoffs

feral spade
#

definately looks like an old writing from some ancient runes

frosty wyvern
#

(I'm kidding)

feral spade
#

lol

sick hound
#

That is a weird obfuscated implementation of factorial

frosty wyvern
#

hm im curious what bytecode it generates lets seee

sick hound
#
  1           0 LOAD_CONST               0 (<code object <lambda> at 0x00000245DE6C80C0, file "<dis>", line 1>)
              2 LOAD_CONST               1 ('<lambda>')
              4 MAKE_FUNCTION            0
              6 LOAD_CONST               2 (<code object <lambda> at 0x00000245DE6CE270, file "<dis>", line 1>)
              8 LOAD_CONST               1 ('<lambda>')
             10 MAKE_FUNCTION            0
             12 CALL_FUNCTION            1
             14 LOAD_CONST               3 (<code object <lambda> at 0x00000245DE6CE420, file "<dis>", line 1>)
             16 LOAD_CONST               1 ('<lambda>')
             18 MAKE_FUNCTION            0
             20 CALL_FUNCTION            1
             22 CALL_FUNCTION            0
             24 RETURN_VALUE```
brisk zenith
#

most of it.. yeah

#

most of it will be calling lambdas

frosty wyvern
#

: )

sick hound
#

something like (lambda x: stuff) just becomes load code object, load '<lambda>', make function

#

the code object has whatever's in the lambda

feral spade
#

thanks for the code samples 😃

brisk zenith
#

oh no, you don't want those code samples

#

those are baaad samples

#

intentionally for fucking your mind

feral spade
#

🤔

unique shoal
#

like actually seriously, don't learn from this channel

feral spade
#

oh ...

unique shoal
#

that's why I said you should take your question elsewhere

#

this is very specifically a channel for using pieces of Python improperly

sick hound
#

this channel is for weirdness and obfuscation

feral spade
#

thanks 🤝

pure dew
#

that lambda mess is just a y combinator

#

making a recursive function out of a non-recursive function

brisk zenith
#

yeah i figured that.

pure dew
#

its much simpler in a functional programming language

brisk zenith
#

i assume because python's lambdas only allow for a single statement?

unique shoal
#

expression

brisk zenith
#

sorry, expression :D

#

(i never knew the difference)

unique shoal
#

statements and expressions are opposites! you gotta use the right one!

brisk zenith
#

(please do enlighten me)

cunning wave
#

expressions yield a value

#

statements ont

brisk zenith
#

oh okay

cunning wave
#

1+1 yields 2

brisk zenith
#

so x = fuck

#

is a statement

cunning wave
#

functioncall() yields nothing

#

and yes it is

brisk zenith
#

functioncall() yields the return value does it not 👀

unique shoal
#

a statement is a syntactic construct that is incapable of yielding a value

cunning wave
#

return doesnt count as yielding

brisk zenith
#

okay i understand now :D

unique shoal
#

wait Nix are you saying functioncall() is a statement?

#

functioncall() is not a statement

cunning wave
#

huh

unique shoal
#

that's an expression

brisk zenith
#

yeah that's what i was thinking

#

it has a value

unique shoal
#

because you can do this if functioncall():

brisk zenith
#

stuff like def function(): is a statement then

#

i assume

#

yes

unique shoal
#

the functioncall() expression has been incorporated into the if statement

#

yes

cunning wave
#

function calls are statements

brisk zenith
#

no surely they're not 🤔

cunning wave
#

its an expression statement

#

jesus christ

#

but its under simple statements in the docs

#

so its a statement

#

right? @unique shoal

unique shoal
cunning wave
#

fancy

#

so i am right

#

and you are right

unique shoal
#

but referring to a function call as a statement is a weird way to address it

cunning wave
#

python allows me to

unique shoal
#

a bare function call on a line without anything else is an expression that is evaluated as part of an expression statement

brisk zenith
#

now to actually be able to remember which one is which :D

unique shoal
#

so functioncall() isn't inherently a statement, but it's a statement if it's the only thing on the line

cunning wave
#

until we look at the code its both

#

its a quantum statement

unique shoal
#

don't confuse beginners with this lemoneye1lemoneye2

brisk zenith
#

heck

cunning wave
#

beginners dont ask about statemetns and expressiosn

brisk zenith
#

hence why i just did?

unique shoal
#

I fill people in on the details of statements and expressions all the time

cunning wave
#

i dont think you are a beginner

#

well if you tell them the details tell them about the quantum statemetns lucy

#

if they want to know the details

#

¯_(ツ)_/¯

unique shoal
#

the technicalities about expression statements should not be a point of contention raised outside of this channel by anyone that knows what they're doing

#

leave the beginners alone!

cunning wave
#

this is gonna be my new favourite thing to confuse people with

brisk zenith
#

same here

brisk zenith
#
guessing_game = (lambda number: print("Guess the number!") or (list((lambda itertools = __import__("itertools"): itertools.takewhile(lambda guess: ((not ((guess[1:] if guess.startswith("-") else guess).isnumeric() or print("Enter an integer!"))) or int(guess) != number and ((int(guess) > number and print("Guess lower!")) or (int(guess) < number and print("Guess higher!")) or True)), (input("--> ") for _ in itertools.count())))()) or print("First try! Damn!")) and print("Well done!"))

a fully-featured guessing game function in one line (without semicolons ew)

>>> guessing_game(7)
Guess the number!
--> 6
Guess higher!
--> 8
Guess lower!
--> d
Enter an integer!
--> 7
Well done!
>>> 
>>> guessing_game(4)
Guess the number!
--> 4
First try! Damn!
>>> 
#

can probably be simplified/compressed but i'm not too bothered about that haha

cunning wave
#

we should put stuff like that in the next code jam challenge

brisk zenith
#

you mean the obfuscation?

cunning wave
#

that type of one liner lambda obfuscation yes

brisk zenith
#

ooh i would love to help with that.

#

do you like my nick now?

#

it's the same as yours.

cunning wave
#

hm

#

but other people got weird praise the ... statement names

#

because they dont get the meme

#

😦

brisk zenith
#

sad

cunning wave
#

yup

pure dew
#

u mean code golf

brisk zenith
#

hm?

cunning wave
#

no i mean this specfic type

brisk zenith
#

my code isn't code golf

#

at all

cunning wave
#

these specific lambda one liners

brisk zenith
#

it's just one single statement.

cunning wave
#

its a statement with a quantum expression/statement in it

#

its really cool

brisk zenith
#

thank you nix

cunning wave
#

i mena technically most statements except of the quantum ones have quantum statements in them

#

dont they?

pure dew
#

oh

brisk zenith
#

hmm

#

there's very few statements

cunning wave
#

because an expression which might be a statement

#

cant contain another expression

#

so

brisk zenith
#

yeah

cunning wave
#

its doesnt contain quantum expressions

unique shoal
cunning wave
#

statements consist of expressions

unique shoal
#

expression statements consist of expressions

cunning wave
#

but expressioon statements can also be seen as expressions

tropic gulch
#

no

cunning wave
#

yes they can

#

a function call can be a statement or an expression

#

we talked about that before

unique shoal
#

expression statements are expressions that are being read as statements by the language

#

because they aren't a component of any other syntactically defined statement

tropic gulch
#

a function call is always an expression

cunning wave
#

no a function call is an expression statement

#

the language sees it as statement

unique shoal
#

a function call is an expression.

tropic gulch
#

a statement can be e.g. an if or a while or an expression

cunning wave
unique shoal
#

a function call that is not part of any other statement is part of an expression statement

cunning wave
#

this page says it can be a statement

unique shoal
#

can be

#

you said "is"

#

that's not correct

pure dew
#

this is why quantum computers are so expensive

cunning wave
#

no

unique shoal
#

we can't make quantum computers because Nix keeps confusing everyone working on them

cunning wave
#

yes

#

thats the plan

#

im being protective of RSA and friends

brisk zenith
#

so are quantum statements a thing

tropic gulch
#

calls are expressions. they can be used as statements (not are statements) because one possible kind of statement is a plain expression

cunning wave
#

and expression statement is a statement which consists of something which returns a not meaningful thing

#

like None

pure dew
#

not really

cunning wave
#

that is what the page says

pure dew
#

it could return anything

cunning wave
#

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None).

pure dew
#

but if you disregard the result tho..

cunning wave
#

so

#

before we look at the rest of the code we arent sure if the expression is just an expression or an expression statement

tropic gulch
#

it is still a fucking expression

#

you just use it as statement

cunning wave
#

but also an expression statement

#

its both

tropic gulch
#

that is like saying you are a car because you can sit inside one and drive

#

!otname suggest nix-is-a-car

cunning wave
#

no u

pure dew
#

if it drives like a car, it must be a car, right?

cunning wave
#

an expression statement is a statement only consisting of one expression with return values you dont use

#

so

#

if i am inside a car

#

i am an expression inside another expression

#

does that still allow me to be an expression stmnt?

#

at some point we should just compile the grammar with pgen and test ourselves

unique shoal
#

there's nothing to test for, this is just an argument between slightly different and equally valid abstractions of what an expression itself is an expression statement

#

which is not really an argument worth having

cunning wave
#

every argument is worth having

#

even if its just because of having the argument

unique shoal
#

not in this server, friend

cunning wave
#

but we are having lots of that type of conversations and arguments

#

all the time

tropic gulch
#

let's have an argument whether we should have that argument

cunning wave
tropic gulch
#

gets out

cunning wave
#

recursive arguments

#

thats the new shit

unique shoal
#

aiight, no more of this in this channel

pure dew
#

speaking of recursive arguments:

item = (lambda: True).__le__

while hasattr(item, "__le__"):
    item = item.__le__
    
print(item)
brisk zenith
#

speaking of recursive arguments:

def thonk(arg=[]):
    arg.append(arg)
    thonk()
pure dew
#

wew boy

#

wait

#

what if arg isn't a list

brisk zenith
#

shh

#
>>> arg = []
>>> arg.append(arg)
>>> arg
[[...]]
>>> 
#

fun thing about python.

pure dew
#

now tryint pprint on that

cunning wave
#
>>> class X:
...    value = False
...
>>> def func(test=X()):
...    print(test.value)
...    test.value = True
...
>>> func()
False
>>> func()
True
>>>

other fun python thing

brisk zenith
#
>>> pprint.pprint(arg)
[<Recursion on list with id=140380905456904>]
>>> 
#

nix that's obvious

cunning wave
#

cpython actually caches the istances of default args

#

that means both function rely on the same object as default arg

brisk zenith
#

i wouldn't call it caching

#

i'd call it single evaluation

cunning wave
#

i wonder if there is a project out there using this

brisk zenith
#

using what?

cunning wave
#

this feature

#

using the same object for multiple function calls

brisk zenith
#

well yeah, probably.

cunning wave
#

evidence

#

also what would you use that for

brisk zenith
#

i've used it before. i can't remember how, but i have.

cunning wave
#

👀

sick hound
#

Just put linux on a chromebook specifically because my other laptop is really bad.. and i needed an on the go python.. station.?

unique shoal
cunning wave
pure dew
#

because the chromebook can barely run python??

sick hound
#

oof wrong chat fam

#

now i just feel stupid

brisk zenith
#

oh hey no problem :D

#

we all make mistakes, not a big deal.

viral hedge
#
def create_script(n):
    s = ""
    for x in range(n):
        s += f"print({x})\n"
    return s
    
exec(create_script(5))``` 
Ey it counts from 0 to n ![PogWoW](https://cdn.discordapp.com/emojis/473432842731388928.webp?size=128 "PogWoW")
#

woo py lambda x : exec("\n".join(f"print({i})" for i in range(x)))

pure dew
#

heresy

pure dew
#

I'm asking this in here because it's something i don't think you would ever want to do, but I wonder if it's possible

#

Is it possible to "save a slice" to use later without storing the actual indices?
Ex:

slice_decl = [3:5]

substr = ("this is a test string")[slice_decl]

Obviously that wouldn't work, but is something similar possible? (I can store the actual indices just as easily, but I'm curious)

brisk zenith
#

@pure dew ```py

x = slice(3, 5)
"hello"[x]
'lo'

pure dew
#

oh lmao

#

nice thanks

brisk zenith
#

yeah it's pretty simple, no problem.

wicked moat
#

Is there a site where I can practice creating classes?

pure dew
#

@wicked moat https://repl.it search for python3

wicked moat
#

thks

wicked moat
#

I understand the following

a=1
b=2
a=b
b=a
a=2
b=2
#

but how can this

a=1
b=2
a,b=b,a
a=2
b=1
#

work?

cunning wave
#

define work

whole kiln
#

the right hand side is basically a tuple

#

and then you unpack the tuple

wicked moat
#

aaaa, nice

whole kiln
#

you're unpacking it to the same variable names, but in a different order

wicked moat
#

I understand now.

whole kiln
#

so they get reassigned

wicked moat
#

Thks, didnt think of it as a tuple.

unique shoal
#

( #esoteric-python probably isn't the best place for general help questions, @wicked moat. use a regular help channel )

wicked moat
#

sry, will do in future

dense spire
brisk zenith
#

:D

arctic bridge
#

🔥

last bramble
unique shoal
#

ahaha

#

incredibly apt

dense spire
#

if someone asks what this channel is for, just tell'em to check the pins

wind maple
#

Why is the meta class barely python 🤔

dense spire
#

because it hacks a c++ feature into python in a fun way? you find yourself doing this a lot or something?

#

also it's weird. shouldn't it either be cout or have the arrows pointing the other way?

#

or is that the point? I don't know. I'm only in this channel because I barely know python.

#

that's what it's for, right?

sick hound
#

Hello, don't know if it is a right section. I'm building a shared library of Python but my app still needs a lib folder of python libs (.pyc files). How can I prevent it?

#

I mean, can I somehow build it straight into a shared library?

pure dew
#

uhm

#

sounds like you are

#

sounds like you want a static library

sick hound
#

I'm not talking about DLL file. I mean a lib folder.

#

PC/pyconfig.h - Line 83

#

define PYTHONPATH ".\DLLs;.\lib;.\lib\plat-win;.\lib\lib-tk"

pure dew
#

more explanation would help

little patrol
#

Oh my god these pins jesus

#

I really don't know python oof

short dagger
#

How to make your CS teacher who only knows C# sweat when you're asked to swap two variables.
a,b=b,a

cunning wave
#

thats just a nice feature of python

#

not really barely python

sick hound
#

How to make people who know what #esoteric-python is used for sweat
misuse(barely_python)

cunning wave
#

😰

pure dew
#

@sick hound nah its barely_python.__misuse__(barely_python)

sick hound
#

no

#

barely_python.__class__.__misuse__(barely_python)

pure dew
#

why

#

misuse is specific to an instance

sick hound
#

barely_python.__misuse__ already has an instance

#
>>> class Foo: x = 5
...
>>> foo = Foo()
>>> getattr(foo, 'x')
5
>>> foo.__getattribute__('x')
5
>>> foo.__class__.__getattribute__(foo, 'x')
5
>>> foo.__getattribute__(foo, 'x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 2```
#

@pure dew

pure dew
#

oh

#

rite

#

its pseudocode

sick hound
#

good name, sadly

brisk zenith
#

i guess that'll do, yeah.

pure dew
#

aww rip name

unique shoal
#

constantly redirecting people is wearing thin on my patience, so we're gonna try this out

brisk zenith
#

yup. seems like a lot of people struggle to realise that "barely" is not synonymous with "completely unrelated to" :D

pure dew
#

well, those people also seem to have missed a build steps when compiling their kernel

last bramble
#

(not to derail the topic, but some people may not know what esoteric means and they may also not read the channel topic)

unique shoal
#

that's part of why esoteric was picked. if they don't know what it means, they are less likely to come here

sick hound
#

i feel like if they dont know what it means itll prompt them to read the topic

brisk zenith
#

but it seems like some people don't even know what "barely-python" means :^)

arctic bridge
#

In an __init__.py: ```python
import sys; sys.modules['os'] = sys.modules['sys'] = None

#

Next level: ```python
for m in sys.modules.keys():
if not m.startswith('__') and '.' not in m:
sys.modules[m] = None

#

Hehehe: ```powershell

for m in sys.modules.keys():
... if not m.startswith('__') and '.' not in m:
... sys.modules[m] = None
...
import os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: import of os halted; None in sys.modules

pure dew
#

oof

arctic bridge
#
lambda x: __import__('arpreq').arpreq(x)```
#

I am pursuing ever uglier hacks in my pursuit of shorter code lol

frosty wyvern
#

pythonic? never heard of it

arctic bridge
#

That replaces this:

def _arpreq_ip(ip):
    import arpreq
    return arpreq.arpreq(ip)
#
lambda x: __import__('scapy').layers.l2.getmacbyip(x)```
#

"PEP 8: Do not assign a lambda expression, use a def"

#

Hah what's pep 8

frosty wyvern
#

pep8? is that a breed of pepe

arctic bridge
#

Accessing attributes doesn't work in 2.7 tho feelssadman

#
>>> _scapy_ip = lambda x: __import__('scapy').layers.l2.getmacbyip(x)
>>> _scapy_ip('10.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
AttributeError: 'module' object has no attribute 'layers'
#

Oh

#

Just had to change it to scapy.layers

#

t = __import__('scapy.layers').layers.l2.getmacbyip('10.0.0.1')

#

But that still doesn't work in windows

#

have to add l2 as well

#

probably some internal importing stuffs

#

For instance, import scapy.all on windows takes 4-5 seconds, while on Linux it takes less than a second

arctic bridge
#

Replacing spaces with tabs reduced file size by 2KB

#

@frosty wyvern First contest: ugliest code wins

#

Submissions should be of reasonable length, but no points are given for being shorter

frosty wyvern
#

Let's make it ugliest code for a common operation/algorithm/pattern

arctic bridge
#

Perhaps to solve a specified task?

frosty wyvern
#

Ugliest fibonacci?

viral hedge
#
for n in (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811):
    print(n)```
arctic bridge
#

Nah, too basic

viral hedge
#

But it's ugly.

arctic bridge
#

Not enough variation

#

Maybe pub-sub consumer-producer

potent tide
#
(lambda _:[(lambda n:__import__('functools').reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0])(i) for i in range(_)])(int(input('whatever: ')))``` Here you go buddy
last bramble
#

gbuefqi

#

]

arctic bridge
#

That's not really all that ugly though

#

Like, sure, it's compressed

#

But it doesn't physically pain me to read

#

If I have to look away because it's so bad, then it wins

potent tide
#
exec(''.join(chr(ord(i)-1000) for i in "јњёіќААєщѕъьщЈчТуАєщѕъьщЈіТччёѕјїњќччАЏюѝіыќїїєћЏБЖњэьѝыэАєщѕъьщЈѠДіТуѠуЙхДѠуИхГѠуЙххДЈњщіяэАіБДуИДЙхБуИхБАёБЈюїњЈёЈёіЈњщіяэАчБхБАёіќАёіјѝќАЏџѐщќэўэњТЈЏББББ"))```
#

/shrug

frosty wyvern
arctic bridge
#

That wins the double-dabward seal of victory

vestal solstice
#

congrats on improving the name

frosty wyvern
#

Well since some people expressed some interest in the idea of having little shitty code-golf/crapcode/ugly code challenges, which I think could be fun, let's put our heads together and think of what could be a fun first challenge

dense spire
#

oh jesus that looks hard :D

#

but fun!

frosty wyvern
#

ENTRIES ARCHIVED AT: https://github.com/shawnmcla/python-discord-challenges-archive/tree/master/submissions/challenge1

Challenge #1
Reverse Polish notation evaluator Code Golf

https://en.wikipedia.org/wiki/Reverse_Polish_notation

Requirements: A function that takes in a (valid) expression as a string and returns the correct answer

Goal: Shortest working code, with honourable mentions for creativity :)

Restrictions:
 [*] No imports! (not even standard library)
 [*] No lists! (other sequence types are okay)

Example input and outputs:

In: "2 3 + 1 -"
Out: 4

In: "15 7 1 1 + − ÷ 3 × 2 1 1 + + −"
Out: 5

You can enter more than one solution. Feel free to look around for inspiration but no blatant ripoffs.
Feel free to collaborate since there's no real prize other than knowing you wrote some horrible code and that Pep8 weeps in the distance.

Share code directly in chat or via a hosting service if it's too long (e.g. gist). Tag your post with #challenge1 so we can easily search through the chat!
Note: Submissions will be archived on a public GitHub repository so if you enter you give us permission to publish the code :-* 
#

pin pin pinnerino please? 😄

#

@dense spire senpai

viral hedge
frosty wyvern
#

oh there's a challenges channel

devout kite
#

!s enumerate

night quarryBOT
#
![site|s]

Commands for getting info about our website.

Commands:
  faq       Info about the site's FAQ page.
  help      Info about the site's Getting Help page.
  home      Info about the website itself.
  resources Info about the site's Resources page.

Type !s command for more info on a command.
You can also type !s category for more info on a category.
frosty wyvern
#

oh right

#

its inactive

devout kite
#

Workin on an awful code

dense spire
#

it's !t, wrongend

devout kite
#

!tag enumerate

night quarryBOT
#
enumerate

Ever find yourself in need of the current iteration number of your for loop? You should use enumerate! Using enumerate, you can turn code that looks like this:

index = 0
for item in my_list:
    print(f"{index}: {item}")
    index += 1

into beautiful, pythonic code:

for index, item in enumerate(my_list):
    print(f"{index}: {item}")

For more information, check out the official docs, or PEP 279.

devout kite
#

Thanks

dense spire
#

and since you're taking command of this, I've given you pin permissions, @frosty wyvern

#

only in this channel.

frosty wyvern
#

^_^ Thank youuu

dense spire
#

naw, thanks for taking the initiative

#

great stuff

#

is it working?

frosty wyvern
#

Y'know, whatever I can do to give my existence a semblance of meaning.

dense spire
#

or did I mess up the permissions?

frosty wyvern
#

hmm cant pin

dense spire
#

there may need to be a role in play

viral hedge
#

can you arrange him in the hierarchy ?

#

Nvm, tried myself

frosty wyvern
frosty wyvern
dense spire
#

look at you mister manager

frosty wyvern
#

Now hopefully people participate. I probably concocted a challenge that's a little too hard for a first

dense spire
#

actually I get the feeling a lot of people who are drawn to this channel don't mind a challenge

frosty wyvern
#

True. I've seen some crazy ish in here

dense spire
#

you may have set the bar exactly where it should be

#

but we'll see

frosty wyvern
#

anywho thanks boss c:

dense spire
cunning wave
#

I am surprised, what he posted was one of the first things I thought of as challenge

frosty wyvern
cunning wave
#

Is .split allowed?

viral hedge
#

That would return a list, whiiich is not allowed?

cunning wave
#

Yes that's why I'm asking

#

But I'm technically not using a list whisteles

frosty wyvern
#

HMMM

#

Good catch.

#

I would say yes but you can't store the list itself

#

You can split and access

cunning wave
#

So I can for loop it

frosty wyvern
#

-_-

#

NVM NOPE NOT ALLOWED

dense spire
#

:D

frosty wyvern
#

You can loop over another type of sequence tho, like a string 😛

cunning wave
#

:(

frosty wyvern
#

I can't be lenient with restrictions

dense spire
#

if you loop over a dictionary aren't you technically looping over a list?

cunning wave
#

I should just golf a list implementation myself

dense spire
#

haha

#

that'd be fun

plain pawn
#

meta comment: I think pinning solutions makes it difficult to find the challenge

frosty wyvern
#

Yeah these are just random pins from before

plain pawn
#

derp, didn't look at the timestamps oof

dense spire
#

I'd be okay with unpinning earlier random pins, and keeping pins the exclusive domain of shawn the event handler

#

your call, shawn

#

if you wanna use it as a sort of bulletin board, or pin winners or something? that's cool.

cunning wave
#

integration into website when

frosty wyvern
#

I don't mind, I like that we can have a little archive of notable shitty code whether challenge related or not

plain pawn
#

Maybe a subscribeable announcement channel for the challenges themselves? I like the winners/notable code but then we're back to my original comment

#

Or, the other way around, a star board for winners/notable code

viral hedge
#

I'd say create a repo, and keep answers to that

cunning wave
#

Create a hacktoberfest repo

#

If we have weekly challenges everyone can make enough prs to it to get his shirt

dense spire
#

I wanna try to keep this a bit small, but keep the ideas flowing

#

more channels and subscriptions and repos are not right at the top of my list. maybe if this really takes off.

pine edge
#

carnal sin

>>> from ctypes import pythonapi, c_void_p, c_ssize_t
>>> a = (1,)
>>> pythonapi.PyTuple_SetItem(c_void_p(id(a)),c_ssize_t(0),c_void_p(id(a)))
>>> a
((...),)

#

note: this segfaults python2

brisk zenith
#

segfaults are hot.

calm rampart
#

I once found a segfault bug in python 3

#

I was using the get all objects function from gc

#

and there's apparently some temporary tuple object that's used for argument handling, that gets its slots blanked out to NULL when not in use

#

and my code ended up accessing that

brisk zenith
#

yup :D

brisk zenith
#
class SingletonMetaclass(type):

    def __new__(cls, name, parents, attrs):

        instance_attr = f"_{name}__INSTANCE"

        if instance_attr in attrs:
            raise RuntimeError(
                "Singleton classes must not fuck "
                "with the '__INSTANCE' attribute."
            )

        # Create the singleton class and assign its instance
        singleton = super().__new__(cls, name, parents, attrs)
        setattr(singleton, instance_attr, object())
        return singleton


class Singleton(metaclass=SingletonMetaclass):
    def __new__(cls):
        return cls.__INSTANCE

i'm tired :D

tropic gulch
#

oof, no imports sounds reasonable, but no lists???

#

Half of Python is built upon lists

#

I'll have to invest a longer thonk on this... GWchadThonkery

brisk zenith
#

this challenge will be interesting

#

despite it being a golfing challenge, i'm not gonna golf it

#

i just wanna be creative :D

dense spire
#

I strongly encourage any non-golf esoterica

#

because I hate golf

brisk zenith
#

i like it but.. i have different interests atm

wind maple
#

oof no .split()

cunning wave
#

yeah 😦

frosty wyvern
#

You can do without golf, it's already challenging enough 😛

brisk zenith
#

¯_(ツ)_/¯

#

normal people complain about having too many parameters on their function head

#

fuck you, i'm defining a class in mine :^)

left remnant
#

what was the challenge

brisk zenith
#

check pins

#

📌

sick hound
#

I might consider donating a prize if enough people join these challenges

crisp pendant
#

@frosty wyvern wouldn't "2 3 + 1 -" evaluate to -4, or am I dumb?

fallen heath
#

a = 2, b = 3, a = a+b (5), b = 1, a = a-b (4) , return a

crisp pendant
#

Ah I see what I did wrong

brisk zenith
#

you know you're in deep shit if you see <generator object <lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<genexpr> at 0x7fdedf8f3660> in your output.

pure dew
#

lmao wtf