#internals-and-peps

1 messages ยท Page 68 of 1

teal girder
#

I want to learn python is there anything you guys suggest?

orchid flame
#

python```
class foo:
x, y: int

flat gazelle
#

x, y is not unpacking, that is an expression of a two element tuple of x and y

#

if you mean annotating multiple variables at once, like go and nim allow, that would probably be somewhat useful

grave jolt
#

not extremely useful

#

just a new syntax for what is already possible

orchid flame
#

most languages have something similar for variable declaration

flat gazelle
#

well, in python you do not need variable declarations, so it is not that useful

grave jolt
#

I think the idea of declaring variables without giving them a value is just kind of weird...

#

It's only useful in stuff like this

int x;
if (foo < bar)
    x = spam;
else
    x = ham;

but this is easily replaced with a conditional expression

int x = foo < bar ? spam : ham;
orchid flame
#

what about in classes?

#

or if its first defined when it unpacked

sacred tinsel
#

You can do this:

a: int
b: int

a, b = myfunc()

if it helps your IDE or some other use case where it'd be useful

orchid flame
sacred tinsel
#

sometimes I'll do annotations like that to get PyCharm to autocomplete something for me or confirm that something exists but then probably remove them before I commit the code

orchid flame
#

so if i have something like color = Tuple[int, int, int, int] ... r, g, b, a: color = something_i_want_to_know_is_a_color

sacred tinsel
#

I don't think thats valid syntax

orchid flame
#

yes

sacred tinsel
#

or is it?

orchid flame
#

its not

sacred tinsel
#

what is the goal you are trying to achieve?

#

if you want to type check one of them you can annotate them temporarily

#

I don't find myself in situations where I'd need the annotation to be there at runtime usually

#

I would agree that

r: int
g: int
b: int
a: int
r, g, b, a = ...

is awful

orchid flame
#

but in that case if i had 100 places where i did that, id have to change them all by hand if i wanted to swap the ints for floats for example. but in my example id just have to change one line, the color type definition

sacred tinsel
#

normally you would just annotate the return type of the function that is giving you the tuple that is being unpacked

#

or annotate the tuple itself

orchid flame
#

it basically has the same problem as hardcoding values

sacred tinsel
#

so, for example:

return_value: t.Tuple[int, int, int] = some_func()
a, b, c = return_value
#

but this is all assuming that you cannot annotate some_func for some reason

orchid flame
#

you cant do that code

#

oh wait you can

#

but are a,b,c annotated in this case?

sacred tinsel
#

again I think it depends on the end goal, if you for example want mypy or pycharm to know their types then this should be 100% sufficient

#

if it's just for the readers convenience, you don't need to use the annotation syntax, you can just put a comment

orchid flame
#

you make good points

sacred tinsel
#

I haven't used mypy much but afaik if it complains about the inability to infer the return type of a function call from some library, this should be enough to make that go away

#

and then mypy can do its thing with the assumption that those types are annotated correctly

orchid flame
#

there are cases where this isn't sufficient but i guess Special cases aren't special enough to break the rules

sacred tinsel
#

mm yea

#

I've also come across situations where I would have found it convenient to do

a: int, b: int = something
#

but I haven't come across a situation where I wouldn't be able to refactor the code so that I can express the same using valid syntax

feral bane
#

if you're actually unpacking, you probably don't need the type hints

#

[if some_func has annotations that should be enough, for example]

#

if not, you can declare a: int; b: int; c: int on a preceding line

paper echo
#
something: Tuple[int, int]
a, b = something

depending on the situation this could make sense too

woeful ferry
#

@cloud crypt sry

coarse cargo
#

I mean, personally I would just declare types on a seperate line

unkempt rock
#

hi everyone, sorry for interrupting, but i have a code that im trying to figure out and i need some help...

wide shuttle
#

Hello @empty ruin, this channel is for discussing the Python programming language itself, from a higher-level perspective. For help questions, you can claim a help channel or ask your question in one of the topical channels (if one fits). See #โ“๏ฝœhow-to-get-help for more info on how to claim a help channel for your question.

shy vine
#

!tempmute 742079691569234050 14d You're not funny

fallen slateBOT
#

failmail :ok_hand: applied mute to @unkempt rock until 2020-09-07 22:16 (13 days and 23 hours).

signal tide
#

quick question about naming convensions, if I have the force of gravity (Fsubg) would the shorthand variable be Fg (because of the subscript) or f_g (following pep)

pearl river
#

I want to know that question too. To expand on it, how bad on the scale from 1 to 10 would be to use

Fแต

? ๐Ÿ˜›

signal tide
#

see that looks like F^g to me

pearl river
#

that's fair

#

I wasn't able to find a Unicode subscript g, only superscript

signal tide
#

which is weird

grave jolt
#

Fโ‚‰

#

nope, Fโ‚‰ doesn't work :(

signal tide
#

ah yes the force of 9

grave jolt
#

gravity_in_newtons ๐Ÿ™‚

pearl river
#

it's the 9th coordinate of the multidimensional force covector

signal tide
#

^^

#

idk I just find it weird how a massive part of python's use is the scientific community yet there aren't any standards put in place for it

teal yacht
#

I mean, there is, it's PEP8 and it says not to use unicode in identifiers if I'm not mistaken

#

Working on scientific systems doesn't mean you don't use qwerty :P

signal tide
#

I never said anything about unicode lol

grave jolt
#

Fะถ

teal yacht
#

I was referring to the symbols used above, which I guess you didn't propose

#

But still, we have snake case for variables, pascal case for variables etc, imo we're fine as is

grave jolt
#

๐Ÿคท

signal tide
#

under policy

grave jolt
#

I don't really get why anyone would want that.

#

If you're unfamiliar with latin script, it's pretty challenging to write python code.

#

Especially if you're using third-party libraries that have English identifiers and English docs.

#

My native language uses cyrillic script, and I'm not going to name anything using it even at gunpoint

#

But maybe it's too close to Latin script, and people from other cultures have a different opinion.

signal tide
#

but then you can make your names ั‚ะธiัั

grave jolt
#

and this

#

!e

Fะฐlse = True
print(Fะฐlse)
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

True
signal tide
#

that hurts me ngl

#
False = True
if False == True:
  None = False
  print(None)```
fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

teal yacht
#

doubleBlergh the eval uses python2 ????

grave jolt
#

<rant> Unicode support actually made me spend a minute or two debugging my code... Cyrillic and Latin scripts share a lot of character, and I accidentally used a Cyrillic ั instead of Latin c (conveniently, they are located in the same place on the keyboard). And I couldn't figure out why it was giving me AttributeError </rant>

pearl river
#

I've seen at least one person with the same problem in the help channels.

#

I don't really get why linters don't complain about that.

signal tide
#

do they complain about non-ascii in general?

slim island
#

An ide would easily catch that

grave jolt
#

it did, I think

#

But I wasn't sure why it was that way

signal tide
#

also I find it weird how py has all these conventions but ide's don't enforce all of them

#

like in cpp if I have:

return Fg/a; ``` it autocorrects to:
```cpp
return Fg / a;```
pearl river
#

Press the auto-format hotkey and it will.

signal tide
#

is autopep8 installed by default?

teal yacht
#

depends which IDE, pycharm definitely comes with an autoformatter by default

raven ridge
#

black is arguably better than autopep8. It guarantees that it never changes your AST, and it has the advantage of being extremely consistent across everyone's codebase who uses it

#

and the minor disadvantage of being an absolutely atrocious style that no one seems to actually like, but that is technically pep-8 compliant.

teal yacht
#

wait, autopep8 changes the AST ?

#

that's outrageous if true

#

(also fwiw I much prefer black's formatting than like yapf)

raven ridge
#

I know I've seen weird things from autopep8 in the past, but I haven't used it in a long time and can't speak to the current state of it. But I know that black re-parses before and after and makes sure the AST matches before committing anything

grave jolt
#

Ironically, if you automatically format all your code to comply with PEP 8, you automatically violate PEP8.

#
  1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
raven ridge
#

well, yes and no

#

no (sane) autoformatter will rename variables or methods

#

and those are the place where "foolish consistency" tends to come up.

#

In particular: do not break backwards compatibility
is talking specifically about that case.

swift imp
#

Wait what's so bad about black's pep8 style?

spark magnet
#

it's not good for large literals, where you might want to add comments in the middle of a long list, or space elements onto separate lines even if they'll fit on one line.

#

there are problems with pragma comments: black likes to move things around.

peak spoke
#

from the bits I've seen here and from modules I've looked through, the line splitting isn't all that great

swift imp
#

Ah

hidden pewter
#

I like to run things through black. Then go through and change a few things for readability/it not looking horrible

unkempt rock
#

Apart from, https://realpython.com/python-memory-management/ and https://www.youtube.com/watch?v=URNdRl97q_0, are there any more good resources on how python's memory management works?

Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, youโ€™ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Pythonโ€™s internal memory ma...

Nina Zakharenko

https://2018.northbaypython.org/schedule/presentation/19/

As a new Python developer, trying to understand how memory management works in python can feel like a daunting task.

The documentation immediately jumps into difficult to follow concepts, especially...

โ–ถ Play video
spark magnet
#

@unkempt rock those will probably cover everything. do you have specific questions?

unkempt rock
#

Oh, I see. No, I just wanted to see if there were more resources on memory management cause I found it interesting

raven ridge
#

there's some very detailed stuff, if you want...

unkempt rock
#

Thanks, actually wanted that very detailed stuff

#

I'll put these in my list

raven ridge
#

they're pretty dense. Expect to need to watch/read it repeatedly, haha

hollow yew
#

hey babes

spark magnet
#

i'm not a babe, but what's up?

swift imp
#

Hey there goku

hidden pewter
safe hedge
#

Not sure you can really class a decorator as something you "get away with"

hidden pewter
#

It was an example for class decorators, but I still find functions within functions calling functions that was an input strange

teal yacht
#

every major language supports it by now, it's harder to find languages that don't support it actually

hidden pewter
#

Including non-object oriented ones?

teal yacht
#

yes

toxic notch
#

I'm curious, how useful have decorators been to people in real life applications in their day job? Life safer or just a convenience to reduce some lines fo code?

teal yacht
#

functional programming is pretty much based around the idea of having first class functions

hidden pewter
#

I was curious about the uses of decorators in normal applications

safe hedge
#

It's not a class decorator though...

hidden pewter
#

It's a function decorator?

brave badger
#

Decorators do provide some ease to some degree. Never really seen a library with a nice API that doesn't have decorators.

hidden pewter
safe hedge
#

In your code it's a decorator function, decorating a function

boreal umbra
#

@brave badger that didn't implement decorators for the user of the API to use?

#

or which didn't use at least one decorator internally?

brave badger
#

Both can apply in this case

boreal umbra
#

ah

hidden pewter
#

When would you use them internally?

#

I can see the uses for an API though.

safe hedge
#

What do you mean internally?

boreal umbra
#

the code in the library has decorators

hidden pewter
#

^ that

boreal umbra
#

I'm working on a library and I use different decorators a lot internally

safe hedge
#

Plenty of code is going to use decorators internally

signal tide
#

I've been using them internally to check that the user doesn't screw something up

brave badger
#

Writing them for internal, non-user-facing code often helps the maintainers of the library

boreal umbra
#

but I don't implement any

#

oh wait I did

#

lol

#

but it's for internal use

safe hedge
#

@property @staticmethod @classmethod

boreal umbra
#

@property is the one I use most extensively

#

makes the API a lot more elegant

#

I also found a library on pypi called cached property

#

it's similar to @property in that it gives you attribute-like access

#

but the first time you access it, it does however much computation is needed, and caches the result for all subsequent accesses

safe hedge
#

That exists in the stdlib now

boreal umbra
#

what

#

where

#

functools?

swift imp
#

Yeah

boreal umbra
#

nice

safe hedge
#

Since 3.8

boreal umbra
#

oh damn

#

needs to support at least 3.7

#

my library does

hidden pewter
#

I'm at the point now were I'm just learning all the advanced features that I haven't needed yet. This discord is a lot of help ๐Ÿ˜›

boreal umbra
#

not my decision though

hidden pewter
#

I tend to stick one version behind

#

So everything is always updated

boreal umbra
#

for my job I write programs that take a long time to run, and for the most part I run them on one of the servers owned by the uni

#

on the one that has 200 cores, they won't install 3.7

#

it only has 3.6

#

I'm very upset about that.

safe hedge
#

What possible logic is there for taht

hidden pewter
#

Effort

boreal umbra
#

"3.6 is still supported"

brave badger
#

Huh, so functools.lru_cache is pretty efficient when used with expensive pure functions

safe hedge
#

It's not really effort to install multiple python versions on a linux box

signal tide
#

2.x was also supported until recently

#

why not just use that

boreal umbra
#

I dunno, the computers have tens of thousands of dollars worth of hardware

#

so they're slow to make anything available on them

hidden pewter
#

Is there any random thing in python that you think people should learn, but most programmers don't know about?

boreal umbra
#

a lot of people don't learn about sets

brave badger
#

Various PEPs and stdlib stuff

paper echo
#

lazy generators are an underrated python feature

#

sets too

hidden pewter
#

Sets are amazing

paper echo
#

and there are lots of great 3rd party packages that are effectively part of the stdlib for me now

#

such as attrs

unkempt rock
#

Actually, I'm not sure if many people know you can call functions from dicts

boreal umbra
#

I use generators in pretty much everything so from my perspective they're not underrated

#

but I guess a lot of people with extensive backgrounds in not-Python don't use them?

paper echo
#

@unkempt rock yep it's a nice way to "dispatch" based on behavior. using dicts to replace a switch/case statement is a nice trick too

hidden pewter
#

Actually, I'm not sure if many people know you can call functions from dicts
The problem with doing that is it get's unreadable fast

signal tide
#

I've been using the dict/functions for a while now

#

they're super useful

paper echo
#

how often do you actually need a mapping of functions though

boreal umbra
#

I've never actually had a use case for dicts of functions

brave badger
#

Not sure if generators are a Python-only thing but I'm sure that some form of a lazy iteration protocol exists for most languages

boreal umbra
#

but it's cool that you can do it, I guess

safe hedge
#

such as attr

Just use dataclasses

boreal umbra
#

it's also a good way to illustrate that functions are objects.

unkempt rock
#
ops = {
  '+': lambda a, b: a + b,
  .
  .
}

op[input("Operation to use (+ - * /) ")](*map(int, input("a b").split()))
paper echo
#

@safe hedge attrs is supported < 3.7 and has a lot of nice features that dataclasses lack. you can also integrate attrs with marshmallow now (using the desert library) which is hugely useful to me

#

@brave badger do ruby and perl have lazy iterator things?

signal tide
#

salt I usually use them in most of my scripts to call functions from cmd

boreal umbra
paper echo
#

obviously use dataclasses if you like dataclasses, but i will continue to advocate for attrs in most contexts

hidden pewter
#
   def run_function(self, line):
        if line[self.pos] in self.function_list.keys():
            self.function_list[line[self.pos]](line)```
paper echo
#

@signal tide i use Click for that ๐Ÿ˜›

unkempt rock
#

That place scares me

boreal umbra
#

@paper echo I use dataclasses a lot; what are attrs?

unkempt rock
#

There's no way they manually obfuscate python code there, do they?

paper echo
#

@boreal umbra dataclasses but super-powered and they support __slots__: https://attrs.org

#

i have import attr in pretty much every nontrivial python program i write now

signal tide
#

i use Click for that ๐Ÿ˜›
ya that would do it

boreal umbra
#

I mean, if it's more super-powered than dataclasses, isn't that just classes?

paper echo
#

nope

#

the main advantage is significant boilerplate reduction

boreal umbra
#

I see

safe hedge
#

I'm just generally against the idea of adding extra dependencies to my projects

paper echo
#

sure, thats why dataclasses were added

boreal umbra
#

will this free me from having to use the same tuple over and over and over again for __eq__, __hash__, etc?

paper echo
#

i dont mind a handful of well-vetted dependencies

brave badger
#

@brave badger do ruby and perl have lazy iterator things?
@paper echo Not really sure, but there might be.

hidden pewter
#

Anyone ever write python code for speed

safe hedge
#

One reason I still use argparse over click

north root
#

the only langs i know with lazy iterators are rust, python, and i think haskell has them

paper echo
#

yeah haskell is big on lazy iterators

#

@boreal umbra somewhat, you have to do a bit of extra work but less so than if you didnt use attrs

@attr.s(slots=True)
class BusinessLocation:
    """ A business with a single, specific location. """

    name: str = attr.ib()
    """ Business primary or common name (not necessarily legal name). """
    legal_name: Optional[str] = attr.ib(default=None)
    """ Business legal name, if different from the primary name. """
    other_names: List[str] = attr.ib(factory=list)
    """ Other business names. """
    structured_address: Optional[UsaAddress] = attr.ib(default=None)
    """ Business address, as a structured datum. """
    text_address: Optional[str] = attr.ib(default=None)
    """ Business address, as free-form text. """
    id: Optional[Union[str, int]] = attr.ib(default=None)
    """ Unique business identifier """

    def all_names(self) -> List[str]:
        names = [self.name]
        if self.legal_name:
            names.append(self.legal_name)
        names.extend(self.other_names)
        return names

    def has_address(self) -> bool:
        """ Check if either structured_address or text_address is available """
        return bool(self.structured_address) or bool(self.text_address)
boreal umbra
#

Anyone ever write python code for speed
@hidden pewter Python is pretty much all I write in, so it's always faster than writing in other languages for me

paper echo
#

imagine all the horrible boilerplate youd have to write to make that class work otherwise

#

duplicating all the names three times to support slots

#

not to mention the massive useless __init__ definition

hidden pewter
#

so id: id is the same as self.id = id

unkempt rock
#

Ah, the annotations for the class methods remind me of a question. When should you use annotations? Is it appropriate to use them in every function?

brave badger
#

afaik cons lists can be used in place of iterators in Haskell right?

hidden pewter
boreal umbra
#

@unkempt rock I use them for everything that I expect other people will use

paper echo
#
class BusinessLocation:
    __slots__ = ('id',)

    id: Optional[Union[str, int]]

    def __init__(self, id: Optional[Union[str, int]]):
        self.id = id

its like 4:1 LoC reduction

boreal umbra
#

valid arguments could be made that this isn't necessary

unkempt rock
#

@boreal umbra Oh, so it's for readability? Does it optimize the code in any way?

boreal umbra
#

nope, doesn't optimize at all

unkempt rock
#

I see

paper echo
#

@unkempt rock in my opinion you should use them whenever and wherever it makes sense to do so. the python runtime ignores them, but you can use static type checkers to check the types of your code. it helps catch a whole category of bugs that might otherwise be hard to catch

#

even things as simple as typos in attribute names can be easily caught by the static checker, whereas otherwise they might not be caught until runtime

unkempt rock
#

I see, interesting

paper echo
#

static checkers include Mypy (the "original"), Pyre, and Pyright

hidden pewter
#

I remember getting in trouble with a teacher once for writing one long list comprehension on one line instead of a program

paper echo
boreal umbra
#

what was the circumstance, @hidden pewter?

#

The impression I get is that a lot of people who are currently employed in programming education don't actually use Python.

hidden pewter
#

I forgot exactly but it was a bunch of for loops / if statements in a python basics class that I was overqualified for

boreal umbra
#

ah

hidden pewter
#

They said it was a readability issue

boreal umbra
#

how long was the list comp?

hidden pewter
#

I forgot

boreal umbra
#

because if they've never seen a list comp that's kind of on them

hidden pewter
boreal umbra
#

which line?

hidden pewter
#

It's a mini hyper specific programming language

#

Mainly the function class

boreal umbra
#

I don't see the list comp but I'm exhausted and don't trust myself.

hidden pewter
#

It's not in there

#

That was something else

boreal umbra
#

wow I feel gaslighted

fallen slateBOT
#

Hey @unkempt rock!

It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .m4a.

Feel free to ask in #community-meta if you think this is a mistake.

unkempt rock
#

Dude

hidden pewter
unkempt rock
#

It was a pdf

#

Bruh

hidden pewter
#

Do they not allow py

unkempt rock
#

Can't even post a book to help people

signal tide
#

I mean I can read that pretty easily

#

I think if you're not used to 1 liners it might look chaotic tho

unkempt rock
#

Nah, seems pretty fine

#

The variable names make sense

#

Not stuff like x or y that no one could understand

boreal umbra
#

@unkempt rock if you share a book here, it's probably just going to get lost in the chat history, but if it's a book that would be helpful for this community and the publisher is okay with distributing it for free we could talk about putting it on the website for this server.

hidden pewter
#

I spent way to long trying to make that not completely unreadable. I think I succeeded, but it's a bit chaotic

#

That is what happens when you don't know about *args

boreal umbra
#

@hidden pewter it seemed readable to me

signal tide
#

I hate people complaining about having single letters as variables when working with physics stuff

unkempt rock
#

Oh, I see, hm. Well I'm not the publisher so..

#

In physics, it makes sense, but general code ehh

#
a = ...
b = ...
c = ...
#

??

hidden pewter
#

I hate that x y z don't always mean the same thing in space

#

y and z both sometimes mean up and down

signal tide
#

excuse the not py:

const double g = 9.81;
const double G = 6.67430e-11;
double a = 0;
double Fg = 0;
double m1 = -1;
double m2 = -1;
double r = -1;```
unkempt rock
#

This is C++ right?

signal tide
#

yep

hidden pewter
#

I watched someone make python code with c syntax. Why does python support that

unkempt rock
#

?

signal tide
#

cpython/cython

unkempt rock
#

It's Cython

hidden pewter
#

no not cython

signal tide
#

python's also not written in python

hidden pewter
#

they just put ; at the end and used {} instead of :

unkempt rock
#

..What?

signal tide
#

; extends the line (nvm)

north root
#

it ends the line

hidden pewter
#

it can just be slapped on the end like in c were it does nothing, because this is python

unkempt rock
#

Yeah and starts a new one, I thought he was talking about in the map

boreal umbra
#

; ends the statement but if you use it in Python you can have another statement before the new line

unkempt rock
#

You can just do

north root
#

!e

print('hello'); print('world')
fallen slateBOT
#

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

001 | hello
002 | world
unkempt rock
#
somefunc(); someotherfunc()
safe hedge
#

It's not wrong it's just ugly

signal tide
#

also it could've been an OpenGL thing

unkempt rock
#

Ah there

#

Is this python bot open source? I want to see how it evaluates from discord

north root
#

!source e

fallen slateBOT
#
Command: eval

Run Python code and get the results.

Source Code
unkempt rock
#

Thanks

hidden pewter
#

It just takes the text and runs eval

north root
#

it does not lol

#

then anyone could just break the bot

hidden pewter
#

ok then

#

right ok

#

OH I remember on a different server had that. That ended well. Full server mute from bot

signal tide
#

fOnere you guys ever do anything about people trying to delete the bot?

#

like excessively

boreal umbra
#

"delete" the bot?

hidden pewter
#

Is their a way to just sandbox code in python?

boreal umbra
#

you can make a VM if that's what you mean

hidden pewter
#

I meant like running eval without it being able to touch other code

signal tide
#

I cba to find any but I've seen a few people try in bot commands

pseudo cradle
#

@signal tide Not even const double g = 9.80665 smh

signal tide
#

No cause g depends on what body youโ€™re on silly

#

Itโ€™s only 9.81 on earth

#

I might not know what Iโ€™m doing in cpp but I know my physics

pseudo cradle
#

It's 9.80665 on earth

feral cedar
#

just say 10

pseudo cradle
#

It's only 9.81 if you ROUND

#

Because you're LAZY

signal tide
#

Depends where on earth you are

#

Thatโ€™s why itโ€™s approximated

feral cedar
#

the average doesn't depend

pseudo cradle
#

Aren't we all in freefall at sea level at a geodetic latitude of 45 degrees???

signal tide
#

Fg = 1/r^2

boreal umbra
#

what am I reading?

pseudo cradle
#

advanced-physics-discussion

signal tide
#

If youโ€™re farther away from the body, the acceleration decreases in python

pseudo cradle
#

Sure, but the nominal accepted standard for g is 9.80665 m/s^2

boreal umbra
#

it's entirely possible that I don't know what I'm looking at but I would encourage moving over to an off topic if needed.

signal tide
#

Just like how pi isnโ€™t just 3.14 (in python)

unkempt rock
#

Python

#

Has a builtin constant for pi?

#

What

boreal umbra
#

yes

unkempt rock
#

How do I access it?

signal tide
#

In math ya

pseudo cradle
#

Yeah, it does, but it'z LAZY

unkempt rock
#

Oh

#

In math

#

I see

boreal umbra
#

I think it's either from math import pi

pseudo cradle
#

It's just pi: 3.141592653589793

boreal umbra
#

or from math import PI

#

but yeah it's a float

unkempt rock
#

3.141592653589793

signal tide
#

should be a double dont @ me

feral cedar
#

aren't floats doubles?

pseudo cradle
#

Yes

boreal umbra
#

are there any use cases for pi in programming where more decimal places are useful, and which a computer can actually use?

pseudo cradle
#

In fact, this is a double because it's stored in C

feral cedar
#

I guess for scientific computing

signal tide
#

Iโ€™d assume some simulations depend on it being precise

pseudo cradle
#

Original definition is in a C file like so #define Py_MATH_PI 3.14159265358979323846

boreal umbra
#

I remember reading that after some n digits of pi, you can calculate the diameter of the universe to the precision of the diameter of a proton, or something.

pseudo cradle
#

The python code is PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));

half wolf
#

After a while the curvature of space due to relativity is going to make your pi precision irrelevant anyway

pseudo cradle
#

C has long doubles so you can go deeper.

#

I've heard of long double precision needed for some deep mandelbrot zooms

boreal umbra
#

I did a combinatorics problem in Python, the answer of which was an obscenely high number

#

apparently Python stores these as strings, or something?

#

I'm not entirely sure how that helps.

pseudo cradle
#

Because I don't think Python has a data type for over 64 bits of precision

#

So you'd store it as a string

#

Oh, apparently there's a bigfloat library

boreal umbra
#

how does it do math with that?

#

this was just using stdlib

pseudo cradle
#

That makes sense. I'd have to look into the details to figure out how, a naive guess would be that you do math on X decimal places, multiply by 10^X, then do the math on the remaining decimal points

teal yacht
#

integers in python are promoted to bigints if they grow over 64 bits

#

floats don't

pseudo cradle
#

Right

teal yacht
#

but you can use decimal

pseudo cradle
#

or bigfloat

teal yacht
#

I mean, decimal is in the stdlib

#

but I don't doubt that the implementation is garbage

pseudo cradle
#

Can decimal handle more than 64 bit precision?

teal yacht
#

pretty sure cpython doesn't use opengmp or some similar library for big ints already

#

yes

signal tide
#

Regardless chaos Iโ€™m using 9.81, if I need the precision Iโ€™ll change it

pseudo cradle
#

Okay, cool

#

๐Ÿ˜›

#

I was just giving you shit, in engineering we always used 9.81 as well

signal tide
#

engineering

teal yacht
#

e = 3

pseudo cradle
#

But technically it's 9.80665 and we can't get any more precise than that due to reasons

visual shadow
#

pi is always 3, i thought we all knew that

feral cedar
#

pi = e

pseudo cradle
#

No, pie are squared

hard kernel
#

Iโ€™m going to cry

signal tide
#

Hold on imma go throw up rq

hard kernel
#

Hold on imma go throw up rq
@signal tide Are you on the engineering side?

signal tide
#

Oh god no

pseudo cradle
#

apparently not

feral cedar
#

probably more "pure math"

pseudo cradle
#

We engineers are known for our approximations and simplifications

hard kernel
#

I do โ€œpure mathโ€

signal tide
#

We engineers are known for our approximations and simplifications
We know

pseudo cradle
#

Not everyone else has been exposed to the joys of engineering

signal tide
#

engineer something in 5d then get back to me

pseudo cradle
#

I wonder how close you could get to pi if you used bigints and expressed pi as an integer ratio

boreal umbra
#

are we counting computer scientists as engineers? because my desk (which I haven't been to since covid) is next to a chemical engineer's desk and I never know what she's talking about.

hard kernel
#

and chem ๐Ÿคญ atm Iโ€™m looking at electronic energy transfer where energy is transferred from one molecule to another through space via virtual photons hyperlemon

signal tide
#

Chem is pretty nifty (with python or smth idk gotta stay on topic)

teal yacht
#

I wonder how close you could get to pi if you used bigints and expressed pi as an integer ratio
@pseudo cradle well infinitely close

pseudo cradle
hard kernel
#

Iโ€™m building a generalised kMC framework to deal with it

#

Unfortunately; Iโ€™m doing the whole thing from scratch

boreal umbra
#

@signal tide she spent dozens of hours making a spreadsheet about how one chemical was synthesized by different chemists and my job at the time was to figure out how to automate that analysis in Python

#

but the person who was paying my advisor to pay me to do that dipped out when covid hit.

#

which is just as well because I had next to no idea how I was going to do it.

signal tide
#

Thatโ€™s sounds pretty interesting ngl

pseudo cradle
#

hah

hard kernel
#

I wanna do retrosynthetic analysis via graph neural networks

boreal umbra
#

my work is natural language processing but I don't allege to have made any advancements in that field.

pseudo cradle
#

I've always found that fascinating

#

We've come such a long way in the last 20 years

boreal umbra
#

except for the one I'm currently working on, but the only reason I made an advancement there is because I may have beat everyone to some low-hanging fruit.

pseudo cradle
#

I wouldn't have ever thought it was possible, but now I swear at Alexa regularly

hard kernel
#

I have a meeting with my advisors today ugh

pseudo cradle
#

and nice, that still counts

boreal umbra
#

I should probably not make this conversation less relevant to the topic

#

let's see

#

@pseudo cradle have you seen flask-ask?

pseudo cradle
#

Never used flask

#

I'm guessing it's some kind of NLP thing?

boreal umbra
#

it's a Python API for Alexa. "ask" is actually an acronym for "alexa skills kit"

pseudo cradle
#

Oh nice

boreal umbra
#

flask is just a bare-bones library for web dev stuff

#

or something

pseudo cradle
#

Right. I haven't touched webdev

boreal umbra
#

the idea is that you can make your own extensions of flask, and flask-ask is a good example of that

pseudo cradle
#

Okay, cool

boreal umbra
#

in fact by default it won't even handle requests that aren't from Amazon

feral cedar
#

call it fl-ask

boreal umbra
#

lol

pseudo cradle
#

You went there

#

When nobody else would

#

You're a pioneer

boreal umbra
#

flask-ask maps the Alexa API onto Python really well

#

but that's mainly because the Alexa API is kinda garbage

pseudo cradle
#

lol...

boreal umbra
#

so representing what little functionality it gives you can probably be done easily in any language.

#

you don't actually get what the user said

#

each voice command to Alexa that was intended for your program, you get a request

#

and that request doesn't contain anything that could possibly tell you what they, word-for-word, said.

pseudo cradle
#

Huh

#

Then... what's the point?

boreal umbra
#

well

#

when you're designing your Alexa app, you decide what sorts of things that app can do

#

you call these "intents"

#

and you tell Amazon what phrases can evoke those intents

pseudo cradle
#

Hmm

boreal umbra
#

and all you get is what intent was evoked.

#

you can also have word slots, but you have to pre-define what words can go in those slots

#

you get that word

pseudo cradle
#

Making something like this sounds like a great way to differentiate yourself when applying for NPL job at amazon

boreal umbra
#

have you been reading my diary?

pseudo cradle
#

Are you working on applying to Amazon?

boreal umbra
#

I don't think my work would be useful for Alexa though.

#

I'm from where they're building the new Amazon HQ

pseudo cradle
#

Make sure you're up on your leetcode skills, they like to leetcode everyone regardless of level/experience

boreal umbra
#

so working there would afford me the opportunity to move back

pseudo cradle
#

Nice

boreal umbra
#

My attempts to keep myself on-topic aren't effective apparently so I'm going to head out of this channel unless someone has a new topic idea.

fresh warren
#

Help how do you capture the blue ~R and ^M characters from a unix file

#

with regex

#

these characters dont appear the same way

#

theyre just showing up as upside down question mar

#

There are different variations like ~Y or ~R that they might have used which show up as upside down question mark, I need a regex that only captures the upside down question mark

#

i tried just doing [upside_down_question_mark] but the problem is that this is the result of parsing that character, so I need to know what that character was to begin with to capture it

wide shuttle
#

Hello everyone, this is a discussion channel, to discuss the Python programming language itself, from a higher-level perspective

#

It's one of the few channels we really like to keep on-topic for such discussions instead of help sessions

fresh warren
#

Hello Ves Zappa, where do you think it's best I ask this kind of a question then

#

Thank you for your help.

wide shuttle
true ridge
#

Thanks! Am snek who is pretty new at python cuz it's been a year since I last coded

granite bear
#

This is a very advanced discussion lol

carmine heart
#

lol

rotund cove
#

hello. i wonder if there is a (better) way or a style to raise TypeError in a function
e.g.:

def foo(name: str, age: int):
    annotations = foo.__annotations__.items()
    for arg, _type in annotations:
        if not isinstance(locals()[arg], _type):
            raise TypeError("'{arg} must be a '{correctType}', not a '{wrongType}'.".format(arg=arg, correctType=_type.__name__, wrongType=type(locals()[arg]).__name__))```
solar delta
#

Thats not bad lol just would use f-strings

#

it would make it less verbose

#

TypeError(f"'{arg} must be a '{correctType}', not a '{wrongType}'.")

radiant fulcrum
#

I wouldnt use f strings on anything that is going to be used as a external module for things

#

not for a while atleast

solar delta
#

Is there a security risk?

rotund cove
#

so no special style to apply there ?

radiant fulcrum
#

not really

#

tho normally a trailing _ would be used instead of a leading _

solar delta
#

isn't leading _ for instance params in solidity?

radiant fulcrum
#

leading normally to me suggests that its a explicitly unused variable

rotund cove
#

yep wasnt sure about the location of the _

radiant fulcrum
#

trailing is normally to avoid naming collisions

north root
#

leading typically means "private"

solar delta
#

yeah private param

north root
#

and yeah, trailing is to avoid name collisions

#

and why not use f-strings?

rotund cove
#

idk i have never used this before

#

i thought .format works better because it provides the repr of an object or something like that

north root
#

it doesn't

#

not automatically at least

flat gazelle
#

I think he said no fstrings as places still require py<3.6

solar delta
#

fstring is benchmarked to be faster in py>3.6

#

right if it requires py < 3.6 then you cant do it

north root
#

sure it is, but i don't think speed is the issue here

#

I think he said no fstrings as places still require py<3.6
that would make sense, but 3.5 is becoming deprecated soon

rotund cove
#

and used with format notation because when working with variable

north root
#

could you elaborate?

radiant fulcrum
#

I only use .format for the backwards compatibility aspect

rotund cove
#

niceGuy = "{name} is the nicest guy alive"
niceGuy.format(name= "George")

radiant fulcrum
#

and its useful sometimes for easy formatting

solar delta
#

^ thats a very good reason lol

#

This is the equivalent

name = "George"
niceGuy = f"{name} is the nicest guy alive"
north root
#

using .format for templating is fine as well

rotund cove
#

i find it more explicit when i look at my code

deft pagoda
#

I would save the type checking in a decorator, to make your functions nicer to read

solar delta
#

Right.. thats a valid point.

north root
#

i was also thinking of a decorator, yeah

deft pagoda
#
In [13]: from inspect import signature 
    ...: from functools import wraps 
    ...:  
    ...: def ensure_type(func): 
    ...:     sig = signature(func) 
    ...:     ann = func.__annotations__ 
    ...:      
    ...:     @wraps(func) 
    ...:     def wrapper(*args, **kwargs): 
    ...:         bound = sig.bind(*args, **kwargs) 
    ...:         for name, item in bound.arguments.items(): 
    ...:             if name in ann and not isinstance(item, ann[name]): 
    ...:                 raise ValueError(f'got {item}, but {ann[name].__name__} required') 
    ...:         return func(*args, **kwargs) 
    ...:     return wrapper 
    ...:                                                                                                                                                                                                               

In [14]: @ensure_type 
    ...: def test(x: int, y:str): 
    ...:     print(x, y) 
    ...:                                                                                                                                                                                                               

In [15]: test(2.3, 23)                                                                                                                                                                                                 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-98815c19cc85> in <module>
----> 1 test(2.3, 23)

<ipython-input-13-b6238c366328> in wrapper(*args, **kwargs)
     11         for name, item in bound.arguments.items():
     12             if name in ann and not isinstance(item, ann[name]):
---> 13                 raise ValueError(f'got {item}, but {ann[name].__name__} required')
     14         return func(*args, **kwargs)
     15     return wrapper

ValueError: got 2.3, but int required
solar delta
#

ah... you got a float as x

radiant fulcrum
#

I also think people ignore the % formatting systems alot aswell

rotund cove
#

thank you all for the discussion

grave jolt
gleaming rover
#

it would be nice if there was syntactic sugar for [v for k, v in d.items() if k in {k1, k2, k3}]

#

like d[k1, k2, k3] (where d is a dict)

#

so basically numpy-like indexing for dicts

spark magnet
#

d.items()

gleaming rover
#

huh?

#

oh

#

yeah

#

edited

dusty verge
#

You could just subclass dict if you wanted

gleaming rover
#

yeah, but then I wouldn't get that behaviour on literals

spark magnet
dusty verge
#

Just do a check beforehand @gleaming rover

#
if isinstance(key, tuple):
    ...
else:
    ...```
gleaming rover
#

Just do a check beforehand @gleaming rover
@dusty verge huh?

#

no, I mean

#

I wouldn't be able to define dict literals with that behaviour

#

Just do a check beforehand @gleaming rover
@dusty verge and it would be ambiguous

dusty verge
#

wdym by ambiguous

gleaming rover
#

okay, I think that depends on your conceptualisation of passing multiple keys...but unlike numpy indexing, order does not matter, so in this case any iterable should be accepted as a collection of keys...?

#

there should be no distinction between tuples and lists as passed to __getitem__, unlike in numpy

teal yacht
#
d = {(1, 2): "abc", 1: "def", 2: "ghi"}
print(d[1,2])```
#

what would that print

gleaming rover
#

in that case, it would not be possible to distinguish between a tuple key and a tuple as a collection of keys

dusty verge
#

Oh yeah, far out im stupid

#

Lol. my bad mate

#

I forgot that tuples are valid keys in dicts

gleaming rover
#

but honestly all this wouldn't be a problem if we had dict destructuring

#

so back to {k1, k2} = d

safe hedge
#

I guess they could add dict intersection something like : d1 & d2 which could basically be the same as {k, d1[k] for k in d1.keys() & d2.keys()}?

pearl river
#

But & is usually a symmetric operation, whereas this one wouldn't be - it takes the values from the left operand.

paper echo
#

@safe hedge they added it in 3.9 or 3.10

#

@pearl river i dont like that argument, convenience beats purity in this case imo

safe hedge
#

They added dict updating and combination (with | and |=) in 3.9 but I donโ€™t think thereโ€™s intersection?

paper echo
#

oh

#

hmmm

#

| follows the same semantics, rightmost wins

pearl river
#

rightmost?

paper echo
#

i think?

#

a | b if there are overlapping keys the key from b wins

safe hedge
#

@pearl river l understand what youโ€™re saying, but symmetric intersection of dicts seems like a bit of an odd case

pearl river
#

that kinda looks like a weird edge case caused by objects being compared by value regardless of type.

safe hedge
#

I mean, itโ€™s there, but itโ€™s been ignored haha

#

But thatโ€™s a union, not a subsetting.

safe hedge
#

Iโ€™m not convinced that & for dicts should be based on keys alone tbh

pearl river
#

Set intersection (&) is a bit more problematic. While it is easy to determine the intersection of keys in two dicts, it is not clear what to do with the values. Given the two dicts above, it is obvious that the only key of d1 & d2 must be "eggs". "Last seen wins", however, has the advantage of consistency with other dict operations (and the proposed union operators).
yup, exactly the same problem - not symmetric.

safe hedge
#

^Yeah thats what Iโ€™m saying

#

I think & is the best I can come up with, but there would be inherent oddness about it

paper echo
#

yeah so i dont understand why its ok for | and not for &

#

alternatively it could just KeyError when there are overlapping keys ๐Ÿคทโ€โ™‚๏ธ

safe hedge
#

Could you maybe use | and & for keywise and || and && for key+valuewise?

pearl river
#

|| and && don't even exist, do they?

safe hedge
#

Tbh I donโ€™t even really like using that notation for most things because I donโ€™t think itโ€™s that readable to the average python user

pearl river
#

like, they can be implemented, but through a hack with double application of &

safe hedge
#

@pearl river not right now, no

#

Like, I think even if this was an option I donโ€™t really see that doing {k: d1[k] for k in d1.keys() & d2.keys()} is that problematic to write

pearl river
#

also, if dict intersection/union would be implemented, but only explicitly:

d1.intersect(d2)

it would make it far clearer that it's not symmetric.

safe hedge
#

I mean, yes and no

#

Looking at that function I still donโ€™t have a clear indication if it includes all matching keys or just matching key:value pairs

#

You would have to have .keyintersect() and .intersect() maybe

spice pecan
#

What if it would produce a dictionary with the keys being the overlapping keys and the values being tuples of values from both dicts? e. g. {"a": 1, "b": 2} & {"b": 3, "c": 4} == {"b": (2, 3)}

#

Although it's definitely not going to work well if you chain intersections

teal yacht
#

to the deleted message: then dict would not be a good choice in the first place, a set would

paper echo
#

@spice pecan that might be nice behavior for a multi-dict

#

like what the various http libs use for http headers

#

also shoutout to the bidict library which is one of those underrated gems

#

anti-shoutout to the lack of frozendict in the python stdlib

#

and anti-shoutout to the fact that there are 2 competing ordered set implementations on pypi, both based on the same activestate recipe by hettinger

pearl river
#

bidict library
oh, nice.

sacred tinsel
#

that kinda looks like a weird edge case caused by objects being compared by value regardless of type.
@pearl river that's just because they are equal and have the same hash, right?

>>> {0, False}
{0}
flat gazelle
#

well, if 2 things are equal and hashable, they must have the same hash

pearl river
#

yup. They say "the results may be equal but are distinctly different", but it's them being equal that creates that behavior in the first place.

flat gazelle
#
In [5]: fractions.Fraction(1, 2) == 0.5
Out[5]: True

In [6]: hash(fractions.Fraction(1, 2)) == hash(0.5)
Out[6]: True
```I do wonder how that is actually accomplished internally
teal yacht
#
    def __hash__(self):
        """hash(self)"""

        # To make sure that the hash of a Fraction agrees with the hash
        # of a numerically equal integer, float or Decimal instance, we
        # follow the rules for numeric hashes outlined in the
        # documentation.  (See library docs, 'Built-in Types').

        try:
            dinv = pow(self._denominator, -1, _PyHASH_MODULUS)
        except ValueError:
            # ValueError means there is no modular inverse.
            hash_ = _PyHASH_INF
        else:
            # The general algorithm now specifies that the absolute value of
            # the hash is
            #    (|N| * dinv) % P
            # where N is self._numerator and P is _PyHASH_MODULUS.  That's
            # optimized here in two ways:  first, for a non-negative int i,
            # hash(i) == i % P, but the int hash implementation doesn't need
            # to divide, and is faster than doing % P explicitly.  So we do
            #    hash(|N| * dinv)
            # instead.  Second, N is unbounded, so its product with dinv may
            # be arbitrarily expensive to compute.  The final answer is the
            # same if we use the bounded |N| % P instead, which can again
            # be done with an int hash() call.  If 0 <= i < P, hash(i) == i,
            # so this nested hash() call wastes a bit of time making a
            # redundant copy when |N| < P, but can save an arbitrarily large
            # amount of computation for large |N|.
            hash_ = hash(hash(abs(self._numerator)) * dinv)
        result = hash_ if self._numerator >= 0 else -hash_
        return -2 if result == -1 else result```
flat gazelle
#

neat

teal yacht
#

I'm a bit confused about the hash(hash(x)) part

#

oh it's explained i can't read

pearl river
#

you know it's a clever implementation when there's 20 lines of comments for 9 lines of code ๐Ÿ˜…

teal yacht
#

no nvm i still don't get it

#

isn't hash idempotent ?

flat gazelle
#

I am pretty sure the first hash is just used as modulo

#

ah, you misread, it does hash(hash(x) * y)

teal yacht
#

oh duh

sly geyser
#

Hi, I need help with python

#

Does anyone know how to code:
A guessing game that uses alphabets in place of digits to make a puzzle out of the addition of two single-digit numbers and the answer. The letters a to j are randomly ordered and each digit 0 to 9 are represented by corresponding letters by position. The player solves the puzzle by guessing which digits fit into the puzzle.

half wolf
#

@sly geyser This isn't the place for homework. Yes we know how to code simple games. This isn't the place for that.

sly geyser
#

Ok thanks wrong group then

unkempt rock
#

anyone here with an experience of scraping pdfs? i want to parse pdf tables with very odd formatting, there are 2 types of column in one table (!) each of different width, multirow cells and also multicolumn cells, on top of that tables span across multiple pages
any ideas how to approach this task?

paper echo
#

@unkempt rock this isnt really the right channel for that, maybe ask in #tools-and-devops ?

unkempt rock
#

@paper echo alright, i'll head there, thanks

paper echo
#

seems like a messy problem too, so good luck

boreal rune
#

how accurate are python's floating points?

#

like, isn't there a number of digits that it can't represent past?

teal yacht
#

they follow ieee754

feral cedar
#

they're doubles

boreal rune
#

oh lol

#

oh it's 15 and 7 for doubles and floats respectively

feral cedar
#

huh?

flat gazelle
#

they do not have decimal significant digits

slender dome
boreal mantle
#

whats something that can be used for background tasks in python

#

celery? or other alternatives out there

grave jolt
slender dome
#

depends on the background task. a simple cron job can suffice if that's what you need. celery is fine too but it's hard to configure. you could also look at message queues, i.e. ZeroMQ or RabbitMQ, and set up a pipeline.

rare wren
#

Guys I want to ask, how can I send email without using smtplib? Because I have a python interview. He told me for making python scripts using standard python library for sending email but not using smtplib. It can be a honor if you guys can give me a solution. Thanks

modern frigate
#

Guys I want to ask, how can I send email without using smtplib? Because I have a python interview. He told me for making python scripts using standard python library for sending email but not using smtplib. Any solution guys? Thanks
@rare wren make a request to gmail api

gleaming rover
#

so I was thinking...is pass really necessary?

#

what if ... was used in its place?

#

so like:

def stub():
    ...
ocean palm
#

pretty sure id give an error

shy vine
#

!silence

fallen slateBOT
#

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

shy vine
#

Read the channel topic

#

!unsilence

fallen slateBOT
#

โœ… unsilenced current channel.

idle isle
#

he used on emoji lmfao

stoic wyvern
#

elipses typically mean that something is abbreviated, or that there is more information available, so it doesn't really fit with being the same as "pass"

idle isle
#

one*

dusty jungle
#

no i deleted it

idle isle
#

ohh

dusty jungle
#

just in case

shy vine
#

!tempmute 360548278313549825 12H Continued off topic noise in topical channel

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied mute to @dusty jungle until 2020-08-27 13:48 (11 hours and 59 minutes).

idle isle
#

right im working on a python project

gleaming rover
#

pretty sure id give an error
@ocean palm no, it would not.

#

a literal in statement position is not a syntax error

#

but neither does it do anything

ocean palm
#

i didnt say i know it would

#

i just said im pretty sure

gleaming rover
#

yup, so I'm clarifying that it wouldn't

#

elipses typically mean that something is abbreviated, or that there is more information available, so it doesn't really fit with being the same as "pass"
@stoic wyvern or that something "remains to be filled in"

#

like my PoV is that there are actual good uses of the word "pass", and it wouldn't be backward compatibility-breaking

#

and honestly adding ... just for numpy is a little weird

stoic wyvern
#

Hmm, upon looking up the definition of ellipsis, yeah that could work

ocean palm
#

numpy is so worth learning for python

#

like it just removes the while

#

whole

#

speed concern

#

cuz itd C code

#

but its so much easier to work with

gleaming rover
#

yeah, numpy is pretty beautiful

#

the indexing alone is a work of art

ocean palm
#

mhm

#

im learning pandas rn just to get to matplotlib lol

gleaming rover
#

hm

#

you can use matplotlib purely with numpy

ocean palm
#

...fr?

gleaming rover
#

depends on what you want to do

ocean palm
#

ok im using a pdf and i sneaked rly far into it and

#

aparently u can do

#

3d graphs

gleaming rover
#

yup

#

it's kind of an extension to MPL so it's a bit twitchy, but you can

ocean palm
#

again havent gotten there yet

north fox
#

#bot-commands

gleaming rover
ocean palm
#

yea good idea

hybrid path
#

I saw you guys talking about matplotlib and numpy ? I learned Matlab and it's really similar but python is free so i was wondering if there is any cons ? Or why would they make matlab with a paied license ? is it faster or something ?

loud tapir
#

isnt it double license tho? Like - paid for companies and free for non-business use

gleaming rover
#

I saw you guys talking about matplotlib and numpy ? I learned Matlab and it's really similar but python is free so i was wondering if there is any cons ? Or why would they make matlab with a paied license ? is it faster or something ?
@hybrid path not really.

#

I mean, there are differences in usage

hybrid path
#

isnt it double license tho? Like - paid for companies and free for non-business use
@loud tapir no i think it's only free for students if your university purchased the education license but otherwise i don't think it's free

#

I was curious because i am seeing more and more AI papers using Matlab for there demos instead of Tensorflow and Python

safe hedge
#

The real question is why you're not using R for making graphs ๐Ÿ‘€

unkempt rock
#

Is R better for graphs

safe hedge
#

@unkempt rock each to their own tbh. But imo ggplot is still the best static graphing library

#

I have used plotly in both R and python for making HTML graphs and I do find python easier when generating more dynamic plots

unkempt rock
#

so Iโ€™m not an experience programmer at all but what are the advantages of R

#

I know that itโ€™s mainly for statistics and data science

#

Anyone got a 3.8 alternative for Kivy since it wasnt ported?

safe hedge
#

@unkempt rock we probably shouldn't have an extended discussion on that here. But ultimately it tends to be better for implementations of statistical testing

modern frigate
#

Hey guys, I was trying to help @rare wren with a job question. he has to send an email without smtp, but idk how to help him and i dont really want to let him down. ive found it kinda difficult

#

using only the standard libraries

#

and yes, ik that smtp is part of the standard library ๐Ÿ™‚

safe hedge
#

I'm not really clear what you mean tbh

#

Do you want to send the email without using SMTP at all or just without using the stdlib smtplib?

rare wren
#

Do you want to send the email without using SMTP at all or just without using the stdlib smtplib?
@safe hedge
Using another standard python lib except smtplib bro

safe hedge
#

I mean... You could just use subprocess to call mail or whatever from the commandline

#

Seems like a bit of a cheat though

rare wren
#

I mean... You could just use subprocess to call mail or whatever from the commandline
@safe hedge

Hmm can you elaborate me bro

safe hedge
#

Seems like a pretty tricky question for a job, not that I really do anything advanced with email, and if you are really struggling with it you might want to consider whether it's a role that's best suited to you

loud tapir
#

I mean... You could just use subprocess to call mail or whatever from the commandline
@safe hedge you can use subprocess to call literally everything. But there may be some os-exclusive shenanigans in tools you are calling, so its generally not a good idea, unless necessary

safe hedge
#

I'm well aware of that. But honestly I suspect calling subprocess and running a standard mail tool is actually going to be wayyyyy more robust than trying to roll your own smtplib alternative

#

The real question is would whomever is asking the question consider that an acceptable answer

safe linden
#

I mean, isn't the whole reason one is using python to do it as compared to other languages likely related to the robust imports you have access to?

safe hedge
#

Yeah

#

I once had an interview task that involved manipulating some text and csv files. I used csv from the stdlib to parse them and the interviewer asked me if I would normally just import libraries to solve a problem. Like, yeah, do you really want me to spend my paid time redesigning the wheel pal

safe linden
#

also stdlib seems like a pretty safe dependency as well...

#

oh, @loud tapir I don't know if you ever responded to my question about interpreters in the python-general chat, but I completely missed it if you did

#

I looked away for a few minutes, and, well

loud tapir
#

oh, @loud tapir I don't know if you ever responded to my question about interpreters in the python-general chat, but I completely missed it if you did
@safe linden I was just hoping that someone else will response :D

safe linden
#

ah gotcha. one person did and they set me on the path of reading about CPython, that's why I missed general. I think my main mistake of thinking there was a single standard for interpreters has been corrected. I can probably follow up more with that on my own.

#

I'm still sort of convinced that numpy arrays are actual arrays and python arrays are just structs though

pseudo cradle
#

Aww, I missed the matlab/numpy/pandas chat

#

numpy arrays are actual arrays

loud tapir
#

some behaviour of interpreters is exclusive to particular interpreters, so I assume most of things are up to whoever make them

pseudo cradle
#

the data is stored consecutively in memory

#

I'm not sure about the Array class in Python, but if it doesn't let you declare a datatype then it's just an array of pointers

west bronze
#

i am getting 2 syntax errors

#

idk how to solve

#

!e

fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

pseudo cradle
#

Huh, !e restriction in advanced discussion is interesting

safe linden
#

@pseudo cradle I am confident numpy arrays are, but are the default python arrays actual arrays?

pseudo cradle
#

I believe they are, since you have to declare a data type

#

If you didn't have to declare a data type it would be a dead giveaway

safe linden
#

But they don't require a length set, and they seem to accept additional elements?

pseudo cradle
#

Yeah, everything I'm reading here indicates to me that they are. Oh, I see what you mean.

#

I'm guessing they're dynamic arrays

safe linden
#

so i guess my better question

#

are python arrays concatenated in memory?

#

and that answer is maybe "depends on the interpreter"?

pseudo cradle
#

I'm reading through this

#

This is what python arrays do

safe linden
#

thank you very much

pseudo cradle
#

๐Ÿ‘

raven ridge
#

Both CPython array module arrays and Python lists are dynamic arrays. list is a dynamic array of object references, and array module arrays are dynamic arrays of fixed size native objects like 32 bit ints

fervent rain
#

What is the best approach to create a rule engine with concrete rules ? Like java has drools

surreal idol
#

How to send email only with socket ?

flat gazelle
#

@safe hedge

In [32]: def test():
    ...:     c = 3000
    ...:     d = 3000
    ...:     print(c == d)
    ...:     print(c is d)
    ...:
In [33]: test()
True
True
In [34]: test.__code__.co_consts
Out[34]: (None, 3000)

(cont from #community-meta )
functions cache all constants in their code. If you for example had

In [35]: def test():
    ...:     c = 3000
    ...:     d = c + 0
    ...:     print(c == d)
    ...:     print(c is d)
    ...:

In [36]: test()
True
False

it does not do that, because d is computed anew, rather than just loading the cached constant

safe hedge
#

@flat gazelle Ah nice. I assumed it must be something like that. I guess that's the same reason

a = 257
b = 257
print(a is b)

and

a = 257;b = 257;
print(a is b)
#

behave differently

flat gazelle
#

ye, the shell compiles line by line

paper echo
#

!e ```python
from dis import dis
def f():
return 5e12
dis(f)

fallen slateBOT
#

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

001 |   3           0 LOAD_CONST               1 (5000000000000.0)
002 |               2 RETURN_VALUE
paper echo
#

!e ```python
from dis import dis
def f():
return 5e12
def g():
return 5e12
print( f() is g() )

fallen slateBOT
#

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

True
paper echo
#

nice

brisk warren
#
TypeError: a bytes-like object is required, not 'str'  ```

Can anyone help me to fix this issue?
paper echo
safe hedge
#

@paper echo I think you've been bamboozled:

>>> def g():
...     return 5e12
... 
>>> def f():
...     return 5e12
... 
>>> print( f() is g() )
False
paper echo
#

๐Ÿ˜ฎ

safe hedge
#

@flat gazelle explained it in the #community-meta channel where I originally asked about this

flat gazelle
#
In [42]: def test():
    ...:     from dis import dis
    ...:     def f():
    ...:         return 5e12
    ...:     def g():
    ...:         return 5e12
    ...:     print( f() is g() )
    ...:

In [43]: test()
True
```same thing as before
safe hedge
#

It's because the code is compiled when you do !e

brisk warren
#

@paper echo don't have permission to ask on that channel

paper echo
#

@brisk warren read the content there.

#

ah, bamboozled indeed

#

fwiw how often are we running python code that hasnt been pyc'ed first?

undone hare
#

Is that even possible?

flat gazelle
#

it is not

paper echo
#

apparently in the repl? or do i misunderstand what we mean by compiled

flat gazelle
#

in the repl, each function gets compiled separately

paper echo
#

is the idea that any code that gets compiled in the same pyc file will share constants?

flat gazelle
#

I would expect the only way to get f() is not g() is to have them in distinct files

undone hare
#

And the code gets compiled line by line in the REPL, so it gets optimized, but each line separately

flat gazelle
#
In [44]: exec("""from dis import dis
    ...: def f():
    ...:     return 5e12
    ...: def g():
    ...:     return 5e12
    ...: print( f() is g() )
    ...: """)
True
```even in a module they share constants
#
In [45]: exec("""def f():
    ...:     return 5e12""")

In [46]: exec("""def g():
    ...:     return 5e12""")

In [47]: f() is g()
Out[47]: False
safe hedge
#

@flat gazelle or just running it in the interpreter:

>>> def g():
...     return 5e12
... 
>>> def f():
...     return 5e12
... 
>>> f() is not g()
True
>>> 
flat gazelle
#

ye, but that does not happen in actual code

safe hedge
#

This behaviour is all just an implementation detail anyway right

flat gazelle
#

yes

stoic trail
#

Does anyone now a good library to play audio streams from internet radios?

loud summit
paper goblet
#

Who pinged me in general?

loud summit
#

I fail to see hows that relevant to this channel

paper goblet
#

;(

mighty hound
#

random.seed = (os.urandom(1024))
python
can anyone explain what it mean??

undone hare
#

You change the seed of the random module (the base for all the random output, with the same seed you'll have the same result) to be a random value provided by the OS, considered safe but slow

#

You don't need parenthesis around os.urandom(1024) btw

#

And... We are in the wrong channel, my bad

blissful vault
#

Decided to move my question here as general seems really active atm (still).
so, about Python GUIs.. Not sure if Iโ€™ve asked this before...
Edit: moved again

wide shuttle
#

There are a lot of Python bindings for GUI frameworks out there; there's probably something you like. A lot of people like QT. Also, you won't get a lot of response here, because this channel is meant to discuss the Python programming language itself, from a higher-level perspective. If #python-discussion is too crowded, consider opening a help channel or using the #user-interfaces topical channel.

blissful vault
#

Crap I didnโ€™t see that channel. Would you be okay if I moved it again (and maybe delete from here)? @wide shuttle

wide shuttle
#

Sure

blissful vault
#

๐Ÿ‘

surreal idol
#

How can i get Smtp server and port from email address in python ? I wanna make email service with that.

radiant scroll
#

you should be able to make a listener on some given host and port with that library,
from there it should be easy to access the calls to it

surreal idol
#

I wanna do like when email sender is "bussiness@mywebsite.com" then i will get smtp server that email.
@surreal idol is that possible ?

edgy frigate
#

i developed a solution on a raspberry pi but the company wanted the code written in C# i searched online and i found ironpython but i don't really have an idea if this is possible to convert python code to c# without rewriting the code, your thoughts and your suggestions?

narrow kettle
#

no its not really possible

#

ironpython is a maybe, but python3 support is still not ready

#

and even then, i dont believe iron python converts into c#

#

ironpython is an implementation of the python lang that communicates with .net framework, and in that vein im not sure if it even has core support

#

which if you are on a pi is probably what you want

#

basically im saying you have to rewrite it

maiden crystal
#

guys i am doing a project which uses Real time video processing please share some document cxz google is not helping what i have to do with RTVP is to count the no of vehicles\

unreal jackal
#

Hi everyone! I have a question to ask.

#

I have been programming in Python 3 for last 3 years, and I love it.

sturdy timber
#

@unreal jackal See #โ“๏ฝœhow-to-get-help for more general questions, unless what you were going to say fits the topic

Discussion on the use cases, implementation and future of the Python programming language including PEPs, advanced language concepts, new releases, the standard library, and the overall design of the language.
blazing sierra
#

I want to make a kinda generic threading system where you pass in a multiple-parameter function, and one parameter becomes a list, and thatโ€™s the thing you thread on, with futures

#

Surely this is a solved problem

#

Just need some help/guidance

#

I want the generic threader to return a list of results whose elements would correspond to each individual function call

flat gazelle
#

so it would be something like

pool([f1, f2, f3, f4]) -> [f1(), f2(), f3(), f4()]
```?
blazing sierra
#

Kinda, yeah

#

And then I want to be able to describe f1, f2... as a list of functions built on a list of one selected parameter of f

#

So if its f(x, y) I want to be able to say f1 = f(X1, y), f2 = f(x2, y) etc etc

#

Or could be y1, y2, etc

undone hare
#

Isn't that just the map function of the multiprocessing library?

paper echo
#

is there some sane way to execute python from the command line such that the last executed expression/statement is returned, like in the python console & ipython?

#
python -c "x=3; y=4; x == y"

something like this, but where the result of x == y is printed without having to explicitly wrap it in print( ... )

#

can i do this with the code module somehow?

#

!d g code

fallen slateBOT
#

Source code: Lib/code.py

The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.

flat gazelle
#

if you just want to see the result and not use it in a script, piping to python -i does do something marginally similar, but it is not great solution by any measure

paper echo
#
python -c 'import code; code.InteractiveInterpreter().runsource("x=1;y=2;x==y")'

i think i got it ๐Ÿ˜„

flat gazelle
#
PS C:\Users\adamh\Documenty\politika> echo "x=5;y=6;x+y" | py -m code -q
>>> 11
>>>
now exiting InteractiveConsole...
``` still noisy, but probably somewhat usable
paper echo
#

oh interesting

#

is that in the docs?

#

it would be nice if they had a flag to disable the >>> stuff

#

and the "exiting" message

visual shadow
#

I feel like I remember there was a way to change that symbol

flat gazelle
#

that seems worth suggesting, probably not a PEP though

visual shadow
#

Actually I'm quite confident it's a variable that can be set.

paper echo
#

nah could be a good patch for 3.10 though

#

not to mention documenting -m code...

#

i have uh

#

a "bad idea" in mind

#

im writing in ZSH right now but it could/should be rewritten in python itself

undone hare
#

Aren't the >>> an env var?

visual shadow
undone hare
#

Ooh

#

So you can add a __import__('sys').ps1='' for more un-readability

visual shadow
#

I was half afraid of what the esoteric community would do with it as I shared that link, not gonna lie ๐Ÿ˜…

undone hare
#

could have been way worst ยฏ\_(ใƒ„)_/ยฏ

#

But I'm sure we can do some stupid things with that

deft pagoda
#

I subclassed interactive console when making a kivy python interpreter --- prompts could be set as class variables

visual shadow
#

Could easily insert a mangled unicode string there and python wouldn't bat an eyelid while the end user would think something is seriously wrong.

flat gazelle
#

could run arbitrary code too

#
>>> import sys
>>> class U:
...     def __str__(self):
...             print('ping')
...
>>> sys.ps1=U()
ping

ping
print('Hello World')
Hello World
ping
undone hare
#

Guys..

#

Does the right-to-left modifier works haha

flat gazelle
#

depends on the terminal emulator, windows terminal probably yes, other windows no, linux I have no idea

mint tinsel
#

how do you guys do switch case in python

#

i hate writing if/elif chains

feral cedar
#

they don't exist like they do in a language like java

feral cedar
#

wow

spice pecan
#

There's a @salt-die code snippet for everything, apparently

deft pagoda
#

you're not wrong

flat gazelle
#

you can use dictionaries for a similar purpose

deft pagoda
#

there's also the new pattern matching pep

#

I hope this is implemented

sacred tinsel
#

this would be pretty cool yes, but dicts do generally get the job done I think

deft pagoda
#

they just don't have fall-through, i don't think the pattern matching does either

#

or maybe it does

#

i'd have to re-read it

sacred tinsel
#

I think it does, if I remember correctly

#

actually now I'm not sure

#

ok it doesn't apparently

#

However, we don't want to mislead people into thinking that match/case uses fall-through semantics (which are a common source of bugs in C).

#

Essentially this is equivalent to a chain of if ... elif ... else statements.

deft pagoda
#

I made the very academic switch case above just to have a fall-through

#

I don't have a use-case for it though, probably way too meta

pseudo cradle
#

Heh, definitely a common source of bugs in assembly, but even then it's an expected desired trait in a lot of instances

hidden pewter
#

Does anyone like or follow pep8's 80 char rule per line?

flat gazelle
#

I do sometimes follow it in simpler projects, but in a lot of cases you want a more sensible maximum

hidden pewter
#

I heard some people like 240

flat gazelle
#

240 is far too much unless you have really long names

north root
#

240 is wayyyy too long

#

some people go for 100 or 120

flat gazelle
#

general guideline I use 90-100, 110 when calling long names

hidden pewter
#

it is annoying with long var names

flat gazelle
#

the only reason I sometimes stick to 80 is because that is the default and for simple projects changing it is a PITA

peak spoke
#

120 is the most I've seen used widely, there aren't that many things that will have a better readability beyond that

swift imp
#

130 is like tops imo

peak spoke
#

If you're running into line len limits because of long var names then it may be a sign that they're a bit too verbose

hidden pewter
#

typing this does not work well when you use the 80 char limit python self.write_value = self.epp_variables[template_name[0]].var_output(self.parse_parameters(template_name[1][:-1]))

peak spoke
#

That looks like a fairly busy line that could be separated out

hidden pewter
#

it look so complex beacuse self.long_var_name

flat gazelle
#
a = b[c[0]].o(g(t[1][:-1]))
```is not any better
tacit hawk
#

the line could be breaked up in var_output() call

hidden pewter
#

@flat gazelle There needs to be a fine balance between long and short names

north root
#

i would do something like this

epp_variable = self.epp_variables[template_name[0]]
parameters = self.parse_parameters(template_name[1][:-1])

self.write_value = epp_variable.var_output(parameters)
#

the line you showed is far too crowded for my liking

flat gazelle
#

my point was that it was not complex because long names, even with short names it is a complex expression

hidden pewter
#

I think f1re's example is best for understandability. I don't like creating vars that only get called once though

peak spoke
#

One of the purposes of the line limit is to prevent that many operations in one line, you're doing 3 accesses, 2 function calls, slicing and an assignment all at once

flat gazelle
#

vars the are only used once are perfectly fine

grave jolt
#

Keeping the average length small is also important.

#

If every line is 79 characters long, it's pretty unreadable

deft pagoda
#

i would probably unpack template_name too

feral cedar
#

raymond hettinger's beyond pep8 talk talks about the line length thing a lot

swift imp
#

I think the 79 character length is an archaic restriction that was necessary when wide screen monitors weren't the norm and terminals had fixed text size, etc.

#

Completely unnecessary anymore

#

120ish seems like a good upper end just from practicality and readibility

grave jolt
#

Pep8 lists some advantages of that limit, I think.

#

Mainly horizontally splitting the view.

#

And, as mentioned above, a line that long might be the result of cramming too much in one line.

#

Also, not everyone is going to view the code on a 4k display

slim island
#

79chars wasn't and isn't about widescreen monitors. It's 79 chars because that's how big a standard terminal is

grave jolt
#

This is from my laptop with a 15in monitor, with VSCode set to the dimensions I'm comfortable with. It can only fit 80 columns. If I close the file explorer, it can only fit 108.

crisp thistle
#

btw I'd be super stoked if they upped the pep8 char limit

grave jolt
#

I don't think it would change anything, pep8 is not anyone's boss ๐Ÿ™‚

feral cedar
#

dress up as pep8 for halloween

grave jolt
#

people will just ignore me

final whale
#

The limit I fix myself is 100 to be able to split a standard screen in 2

#

With the added restriction to not nest any function / method calls

grave jolt
#

how do you reach 100 characters then? ๐Ÿ‘€

#
with_a_really_long_variable_name.and_unbelievably_large_method_name(with_a_lengthy_argument_as_well)

?

final whale
#

mostly some long strings

#

and graphql queries that need to take a lot of arguments

deft pagoda
#

i like 120

#

it's where i usually set the vertical bar at

wild cedar
#

Seting up an API with local host using python to use in flutter,
Is only useful before I publish app, because after publishing, I can't run the api for some other and can't keep my computer on,.
So how I do so without spending money on buying a new web hosting or something like that

noble kelp
#

hi--if a library wants to expose a bunch of ideas to the outside world, for example

foo/
  __init__.py
  bar/
    baz.py
    ...

is there a better way for third party applications to do things like from foo import Baz than putting all the imports in __init__.py a la from bar.baz import Baz or is that the prescribed way?

#

looks like flask does it, so i suppose it is

deft pagoda
#

that's how i do it, cause i dunno another way

cloud crypt
#

there isn't really any other solution I guess

swift imp
#

I'm a big fan of including certain things in __init__.py. We have a bunch of pandas accessors at work, and we include them in the top levle __init__ so that when you import the module, the accessors are automatically added to the namespace.

sand girder
#

Is transpiled Python-to-JS allowed? I read through the rules and it says "other code is fine as long as it doesn't implement game logic". Where is the line between what constitutes as Python and what counts as "other code"? Is the transpiled code still Python if the original source code is Python?

This project in particular seems interesting: http://www.transcrypt.org/examples

deft pagoda
brisk salmon
#

How do I implement a python algorithm that bounces when it hits the edge of the screen?

feral cedar
#

if x_cord > x_bound: dont()

signal tide
#

if x_cord > x_bound: dont(); turn_around(); go_back()*

boreal umbra
#

I hope those are built in functions

#

Otherwise you're just moving the work of implementing that somewhere else

signal tide
#

you've never using go_back()? ๐Ÿ˜†

half wolf
#

Moving the work around is like 90% of programming :)

vale summit
#

does anyone know if mypy is the best type checker for python? or is there another one out there?

pearl river
#

there also exists pytype

#

When I asked why mypy is considered the "default" as far as type checkers go, I recieved an answer that was obvious in hindsight:

undone hare
#

Yup, mypy is maintained by the PSF

vale summit
#

oh

#

i know it's not perfect, but at times, it's pretty buggy once you start using more nested types

#

just thought there was a more robust one

radiant fulcrum
#

MyPy can need some beefy hardwear to lint fully

#

otherwise it can be quite slow

gleaming rover
#

PyCharm goes crazy when I start using generic callables

#

why is bool a subclass of int?

radiant fulcrum
#

1 or 0โ„ข๏ธ

gleaming rover
#

I like sum(map(f, iterable)) as much as the next person, but seriously

flat gazelle
#

for reverse compat. Python used to not have a bool and just used 0 and 1

sacred tinsel
#

I like this summary:

To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.

gleaming rover
#

I like languages where they're separate types, I guess

sacred tinsel
#

why?

safe hedge
#

One example of where it would be nice is dicts

#

Do {1: โ€˜aโ€™, True: โ€˜bโ€™}

paper echo
#

@vale summit there is also pyright and pyre

gleaming rover
#

why?
@sacred tinsel kind of smacks of weak typing, I guess?