#internals-and-peps

1 messages ยท Page 43 of 1

undone hare
#

Ah right

grave jolt
#

nevermind, let's get back on topic

true ridge
#

I've just tried to check total LoC on top 2500 packages on PyPI

#

most of them didn't pack tests in the source dists, so it is lower then the stdlib

#

'517661'

#

total of 126592 files

#

4~ LoC per file

versed plover
#

hello. i am new to discord. i am blind. i am ilyas, from algeria. i want to learn python. is this server also for beginers? thanks

gray mirage
#

Hi, yes, this is a beginner-oriented community. We have #โ“๏ฝœhow-to-get-help if you need it, but I'm not sure how well Discord works with screen readers

versed plover
#

print("hello, programmers!")

summer quarry
#

hi anyone online

versed plover
#

it's pretty accessible with nvda, the screen reader

summer quarry
#

can anyone guide me where can i ask question in this server about our python code?

languid dagger
summer quarry
#

@languid dagger thanks man i really appreciate it

pseudo mason
#

Is that a good way of swapping variables or is it a no no

var1, var2 = var2, var1
undone hare
#

It is a good good ๐Ÿ™‚

cloud crypt
#

this is like the epic feature of python

#

haha

undone hare
#

I was expecting you to get some funny itertools stuff to swap them haha

pseudo mason
#

Is it better than using a temporary variable?

undone hare
#

Yup

cloud crypt
#

I think (a, b) = (b, a) could be a bit faster

hasty thistle
#

as in faster execution time?

#

because I don't think it is

peak spoke
#

tuples don't come into play anywhere with those swaps

flat gazelle
#

ye, the bytecode is optimized for that. But for more complex swaps, it does just build tuples

terse orchid
#

Hi. I want to seperate a big class into three classes. For the sake of using memory efficiently, is implemeting them in one single module (file) a good practice? I can provide more info if you are interested in my question.

flat gazelle
#

write them in a way that is most readable and sensible, not in a way that is most "memory efficient". And whether they are in a single module would not impact memory whatsoever

grave jolt
#

It's faster actually

#

!e

import dis
def f():
    a, b = b, a
dis.dis(f)
fallen slateBOT
#

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

001 |   3           0 LOAD_FAST                0 (b)
002 |               2 LOAD_FAST                1 (a)
003 |               4 ROT_TWO
004 |               6 STORE_FAST               1 (a)
005 |               8 STORE_FAST               0 (b)
006 |              10 LOAD_CONST               0 (None)
007 |              12 RETURN_VALUE
grave jolt
#

It does everything on the stack without creating a new tuple.

terse orchid
#

Can I post here 30 lines of code do demonstrate my problem? Or do you suggest to write it in help channel?

north root
#

a help channel would be more suited

flat gazelle
#

you could use semantic versioning and compare major versions

swift imp
#

We update the extraction tool regularly

#

I need to compose my thoughts and come back

#

I'm not doing a good job of describing my problem

unkempt rock
#

is python 2 worth learning ?

slim island
#

no

gray mirage
#

Nope.

final whale
#

is it good practice to rely on Nonetype being falsy instead of checking identity ?

peak spoke
#

Depends on the data you can receive

#

Checking identity is never going to hurt if you expect None though

flat gazelle
#

generally, do check None explicitly, even if it does not matter in the context, always better to build functions that are more reusable

#

though e.g. when dealing with lists and falling back to [], it makes no difference

boreal umbra
#

There's some code I might be using that does a lot with one-hot vectors, and when you need more than one of them at once, they're stored as a list of integers, where the integer represents the index in the one-hot vector that is 1. But I'm thinking that this doesn't necessarily save any memory because there'd presumably only be one instance of the one-hot and the list would actually be an array of pointers.

worldly venture
#

!tempmute @daring lark 12h On top of being off topic in python language, saying you "like to watch porn with Joe" is not appropriate for our community

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied mute to @daring lark until 2020-05-26 05:44 (11 hours and 59 minutes).

final whale
#

I'm not too sure about the channel, but has anyone ever used a phylogenetic tree in order to reduce repetitions when making dataclasses ?

radiant haven
#

What is the best way to learn Python?

slim island
#

The best way depends on you - but this isn't the right channel, I'll write a longer reply in #python-discussion

deft pagoda
#

If one wanted to make a class with __slots__ also be immutable, how would you implement it? I've come up with inheriting from this:

class Immutable:
    """Makes a class Immutable as soon as `writable` is set to `False`."""
    __slots__ = 'writable'

    def __setattr__(self, attr, value):
        """Force immutability."""
        if getattr(self, 'writable', True):
            return super().__setattr__(attr, value)
        raise ImmutableError(f"cannot assign to '{attr}'")
#

i set the writable flag at the end of __init__

#

i guess i can just call super().__setattr__ in the init instead

cunning turret
#

If I'm using the switch statement in python, do the cases have to be numerical?

#

like so if its checking multiple conditions

pliant tusk
#

uh. there isnt switch in python

cunning turret
#

oh, i was looking at this

pliant tusk
#

oh using a dictionary

cunning turret
#

ohh wait sorry i was looking at java code

#

and mixed up

zenith topaz
#

Any hashable value works.

cunning turret
#

so then should I just stick to repeated elif statements?

#

if i want an easier way to implement what a switch statement does?

flat gazelle
#

well, if you scroll down, there are the dict variants

final whale
#

Any reason to use obj.__class__ over type(obj) ?

deft pagoda
#

i like __class__ better when i'm chaining

#

but probably preference

#

that is, self.__class__.__name__ i like more than type(self).__name__

#

but if i just need __class__ i'm happy with type

true ridge
#

this video explains it quite well

final whale
#

just finished watching it, that was super interesting

#

so type(x) doesn't just call _class_

deft pagoda
#

when do we get a builtin name function

#

would be interesting if using it on a normal variable returned the variable name too

#

name(x) = 'x', etc

gentle lodge
#

well a given value might be assigned to more than one variable

raven ridge
#

or no variables, even if there are living references to it.

x = []
y = [x]
del x

The value that x originally refered to still exists, but no longer has a name.

deft pagoda
#

that wouldn't matter

hybrid hare
#

can somebody help me with homework ;/

deft pagoda
hybrid hare
#

ok

pliant tusk
#
>>> def names(val):
...     for obj in gc.get_referrers(val):
...             if isinstance(obj, dict):
...                     for k, v in obj.items():
...                             if v is val:
...                                     yield k
>>> x = []
>>> [*names(x)]
['x']
``` @deft pagoda
lost nexus
#

Neat function

pliant tusk
#

does that count?

deft pagoda
#

does that get __name__ too

pliant tusk
#
>>> def f():pass
...
>>> [*names(f)]
['f']
>>>```
deft pagoda
#

nice

#

can it return more than one name?

pliant tusk
#

yes

#
>>> x = []
>>> y = x
>>> [*names(x)]
['x', 'y']
>>>```
deft pagoda
#

can you match it with the locals name

pliant tusk
#

it will get every name for an object that exists in the current state

#

i mean, yea technically

#

youd need to get the locals for the last frame

#

one sec ill write it

deft pagoda
#

if more than one name, return the one in locals

#

is what i mean

pliant tusk
#

yea i get that

#

i think im gonna have it loop backwards thru the frames locals to look for a binding

deft pagoda
#

could you save the name at the beginning

#

just by immediately searching locals()

pliant tusk
#

well yea

#

but that only handles the immediate scope

deft pagoda
#

wait, then it will have val as the name

pliant tusk
#

i want it to handle all scopes

#
import inspect

def name(val):
    frame = inspect.currentframe()
    while (frame := frame.f_back):
        for k, v in frame.f_locals.items():
            if val is v:
                return k
``` @deft pagoda  that loops back up the frame stack looking for all instances of the var and yielding their names
deft pagoda
#

nice, we can just stop on the first one

#

well, for name

pliant tusk
#

true

#

that should work then

pliant tusk
#
import inspect

def name(obj):
    frame = inspect.currentframe()
    while (frame := frame.f_back):
        for key, val in frame.f_locals.items():
            if obj is val:
                return key

def obj(name):
    frame = inspect.currentframe()
    while (frame := frame.f_back):
        for key, val in frame.f_locals.items():
            if name == key:
                return val
``` incase you wanted the reverse too
tender kite
#

so should different functions be put in different python files? im new

pliant tusk
#

personally i group based on what the code does. like if a couple functions and a class do similar things then i would put them all in the same file

tender kite
#

okay

#

I just don't know how to connect the files togehter

#

lol

pliant tusk
#

import

tender kite
#

ah ok

pliant tusk
#

if we had a file called file.py and a file called main.py we can use import file to use the code from file.py inside main.py

tender kite
#

okay i get it now

#

thank you

#

on e more Q

#

i could call a function that is in file.py?

#

the normal way

pliant tusk
tender kite
#

ohh

#

ok

pliant tusk
#

you would do it like that

deft pagoda
#

i don't think you have to iterate through a dict if you already have the name

pliant tusk
#

you are very correct

#

im just dumb

deft pagoda
#

lol

pliant tusk
#
def obj(name):
    frame = inspect.currentframe()
    while (frame := frame.f_back):
        if name in frame.f_locals:
            return frame.f_locals[name]``` there
hardy belfry
#

random questions. Are "while" statements loops and "if" statements arent, correct?

frozen solar
#

Correct

hardy belfry
#

ty @frozen solar !

unkempt rock
#

#bot-commands

ancient marsh
#

Anyone got time for a hopefully quick Plotly question? Left it in the #data-science-and-ml channel but doesn't seem as active as this channel.

deft pagoda
#

this isn't the channel for it, you can try a normal help channel

ancient marsh
#

@deft pagoda Thanks!

sonic mortar
#

@ancient marsh , we just post our questions in the help channel we get, and then people come once in a while and look at them?

ancient marsh
#

@sonic mortar Great, thanks! New and trying to get a sense of the flow. Being patient ๐Ÿ˜„

sonic mortar
#

is that a yes?

#

haha

#

;p

visual shadow
#

That's a yes. Only use free Help channels to ask your questions

wide shuttle
#

Hey @unkempt rock, this isn't the right channel for such a question; this channel is for discussing Python, the language, itself. For more general chat about Python, we have #python-discussion and for help questions, you can claim a help channel (see #โ“๏ฝœhow-to-get-help).

flat gazelle
#

you can probably do with contextlib.redirect_stdout and stderr and have the bot send msgs into a specific channel

robust path
#

hello

#
# Tableau de genotype
genotype = ['0'] * 16

# Number of people
people_number = 20

# Tableau de population
people = [genotype] * people_number

print(people)

# Random
individu = randint(0, people_number - 1)
papa = randint(0, people_number - 1)
maman = randint(0, people_number - 1)


# Generation de la population
for i in range(0, people_number):
    random_number(people[i])

# Mutation d'un individu
mutation(people[individu])

# Crossover sur deux individus random
crossover(people[papa], people[maman])

# Generation
for i in range(0, people_number):    
    # Conversion binaire to decimal
    x = bin2dec(people[i][genotype[0:8]])
    y = bin2dec(people[i][genotype[8:16]])
    
    # Ajout du cube
    bpy.ops.mesh.primitive_cube_add(location=(x, y, 0))

x = bin2dec(people[i][genotype[0:8]]) how to fixe this line of code plz ?

flat gazelle
robust path
#

too hards to undesrtand

thorn dragon
#

Just learned about the fstring = directive(?), but I can't find any docs about it. E.g.:

#

!eval print(f'{1 + 2 = }')

>>> print(f'{1 + 2 = }')
1 + 2 = 3
fallen slateBOT
#

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

thorn dragon
#

Ope

#

I might just be blind though

neat cliff
#

How'd I use redirect_stdout to see what's in terminal?

spice pecan
#

@thorn dragon it was introduced in python 3.8 I believe, it copies the expression inside the brackets and puts it before the evaluation result

full jay
#

Misread, my bad

#

Thought you were talking about f-strings specifically, not the walrus

thorn dragon
#

Right yeah, it seems to work for me, but I can't find any docs on it. Also it doesn't seem to match the documented fstring grammar

full jay
#

Oh I have a good cheat sheet/site for that

#

Pretty much anything marked as the New Style can be used with f-strings

spice pecan
#

I remember seeing some examples along the lines of "{width=}" somewhere (probably the what's new section), but it probably should be mentioned on the format spec doc page

#

I was also surprised when I found out you could use expressions as format specifiers in f-strings

hushed heart
#

we should i use f stings

full jay
#

It's neat but should be used sparingly. It can get a bit cluttered and hard to read after a while

hushed heart
#

i meant when

full jay
#

Any time you want to toss a value into a string

hushed heart
#

any better alternatives

full jay
#

So when you would do something to concatenate a string or what have you

spice pecan
#

fstrings are the best atm, they are essentially str.format, but faster

full jay
#

Yep

hushed heart
#

thanks

#

pretty neat

full jay
#

The only weakness is that you can't easily make template strings from them

#

But that's a very minor point

thorn dragon
#

And more concise. I think the part that I like most about them is that the put the formatting right next to the value you want formatted

full jay
#

Exactly

#

You see the context without having to check the end of the string and piece together what goes where

#

It's just there and ready to go

spice pecan
#

I like python's implementation of them the most, probably

full jay
#

JS's string interpolation is pretty much the same

spice pecan
#

though I do like how they're done in swift

full jay
#

What's the style in Swift?

spice pecan
#

"text \(variable)"

full jay
#

That feels clunky to me

spice pecan
#

It does look odd at times, yeah, but it's an interesting choice imo

full jay
#

True, it's not the worst

#

And it does make sense, since when you want to do something different, you're usually going to escape it anyway

spice pecan
#

Yeah, exactly, and there's no need to put a symbol before the string either

full jay
#

Or like in JS's case, use backticks

#

Or wait, was that another one...

#

So many languages

flat gazelle
#

raku has a nice system

spice pecan
#

It's backticks as quotes and then ${expr} in JS, yeah

full jay
#

I think for me it's the curly braces that I like

#

They feel different enough that you expect them to do something funky in a string

#

Parentheses are just everywhere, though

spice pecan
#

That's probably why curly braces are so widely used when it comes to formatting/interpolation

full jay
#

True

unkempt rock
#

can anyone think of some pros/cons of using dataclasses.make_dataclass instead of collections.namedtuple?

undone hare
#

A dataclass is mutable, a named tuple is not AFAIK

#

Well, the instantiated object

unkempt rock
#

yeah you're right

#

good call ๐Ÿ™‚

robust path
#

How to do a probibility in python ? I want that thing happen with a probaility of 0.2 for exemple

flat gazelle
#

You can weighted randoms with the random module

robust path
#

how

undone hare
#

Is there any built in support? I wanted to use it last time but I ended up using my own implementation because I couldn't find one on the stdlib

robust path
#

@flat gazelle

full jay
flat gazelle
#

Though if you just want 20% chance for sth to happen, you can do

if random.random() < 0.2:...
full jay
#

Although I'd probably do it with randint() because my brain doesn't like floats

undone hare
#

Aaah nice

cloud crypt
#

my brain doesn't like how floats are represented in binary

full jay
#

Same

radiant fulcrum
#

Right

#

what do you guys recon is the best method of getting the programs current Ram and CPU usage

deep coral
#

Yeah

radiant fulcrum
#

idk but not the channel to rlly discuss that, they'll probably explain it

peak spoke
#

Depends on the os CF8

radiant fulcrum
#

then get a help channel

wide shuttle
#

Yeah no

#

!shhh

fallen slateBOT
#

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

shy vine
#

!unsilence

fallen slateBOT
#

โœ… unsilenced current channel.

radiant fulcrum
#

Depends on the os CF8
i mostly want it to be cross platform

#

tho idm yeeting IOS

#

Linux and Windows would work

#

Originally i thought about using Rust to get it (considering its going to be an embeded thing)

#

but that seemed less hopeful than using python

peak spoke
#

I'd probably look into psutil or something like that because it'll be os dependent

radiant fulcrum
#

can psutils get the list of processes and their usage?

#

Ik it can get overall usage

#

but im looking for getting the specific program's usage

peak spoke
#

I believe it can get a list

#

Found the resource module for unix if that works, but it's prboably not going to be the nicest on windows

potent path
#

I'm trying to find a module for windows that gives block size in bytes of how much space a file takes up on the hard drive.

radiant fulcrum
#

wouldnt os do that?

random tangle
#

(self, nums: List[int]) -> int:
what does this do

radiant fulcrum
#
# get file size in python
import os

file_name = "/Users/pankaj/abcdef.txt"

file_stats = os.stat(file_name)

print(file_stats)
print(f'File Size in Bytes is {file_stats.st_size}')
print(f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}')```
potent path
#

Python has Path.stat().st_size which gives the size in bytes of the file. But that doesn't include the actual amount of bytes taken up on the hard drive.

#

Hard drive space is allocated in blocks by the operating system. And there's also minimum block size for a file.

radiant fulcrum
#

yh ik

#

thats gonna be hard todo unless it directly interacts with the OS

potent path
#

So there's a discrepancy between the actual filesize and how much memory is taken up on the drive.

spiral willow
#

Why do we care?

#

Like block size is all that matter

potent path
#

What do you mean?

spiral willow
#

Why would you care in discrepancy between the two? What do you hope to gather with the data?

potent path
#

I want to know the true amount of space that's being taken up on my hard drive because I'm running low

#

on memory and to see if I can compress anything

spiral willow
#

Compression will only help if you combine files into single zip

potent path
#

I'm also interested in seeing it.

potent path
#

Thanks

spiral willow
#

Steve, you will need to pull allocation size from drive and do the math yourself, Windows apparently does it for you in explorer

radiant fulcrum
#

if you build it in debug mode it will fail to compile

#

i have no idea why

#

but its a thing

meager meadow
#

hello

#
import sys, webbrowser, bs4, requests
print('Searching...')

res = requests.get('https://google.com/search?q=' 'https://pypi.org/search/?q='
+ ' '.join(sys.argv[1:]))
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')
linkElems = soup.select('package-snippet') #element found in each link

numOpen = min(5, len(linkElems))
for i in range(numOpen):
    urlToOpen = 'https://pypi.org' + linkElems[i].get('href')
    print('Opening', urlToOpen)
    webbrowser.open(urlToOpen)```

what does ".get('href') do under the for loop?
polar geyser
#

It extracts the href attribute of the links selected with linkElems = soup.select('package-snippet')

#

<a class="package-snippet" href="/project/test-test-test/"> <- this is what the links look like on pypi.org. And it gets the "/project/test-test-test/" value in the href attribute

meager meadow
#

ah ok

#

what does the second parameter of print do (also under the for loop)

#

the ", urlToOpen"

polar geyser
#

Sorry. I can't walk you through the very basics of python. I recommend you to do a beginners guide

full jay
#

There were less..... dickish ways of saying that, I feel.

#

@meager meadow You might look into some of the resources we have on our site. Automate the Boring stuff and A Byte of Python are both great starting points

#

!resources

fallen slateBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

pliant tusk
#

@meager meadow print can take any number of arguments

meager meadow
#

yea im doing atbs rn, just never used print(something, somethingelse)

full jay
#

Ah I getcha

pliant tusk
#
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.```
meager meadow
#

coolcool

hushed rose
#

what is the difference between an Array and a List?

flat gazelle
#

Which array? array.array, bytearray, numpy.ndarray?

slim island
#

Conceptually, or with respects to Python specifically? Conceptually, an array is contiguous in memory, a list is just an abstract data type higher level than something like memory (i.e can be implemented in different ways)

hushed rose
#

does python have an array data type?

somber halo
#

there's a built-in one yes

flat gazelle
#

The python list is implemented using an array

#

There is also bytearray and the C interop arrays

hushed rose
somber halo
#

let me see

flat gazelle
#

What is your goal. You probably want a list

hushed rose
#

i'm learning c# now and i want to know the differences between an array and a list

#

the practical differences

flat gazelle
#

Oh, ask in ot then. C# probably uses those terms differently than python

#

!ot

fallen slateBOT
somber halo
#

temp_array = array('d', [1., 2., 3.])

hushed rose
somber halo
#

sorry, you need to import the array package

hushed rose
#

oh ok

somber halo
#

from array import array

temp_array = array('d', [1., 2., 3.])
hushed rose
#

yes

#

why the points?

somber halo
#

no reason in particular

hushed rose
#

xD

somber halo
#

just to signal these are intended to be doubles

#

either way

#

In Python, the use of array isn't that common.

hushed rose
#

i know

#

but arrays can't store different type of values right?

somber halo
#

right.

hushed rose
#

oh ok

#

i think that's the main difference

somber halo
#

hence why you declare the datatype when you initialize your array

#

I mean, it could be infered automatically hypothetically

hushed rose
#

ok thank you

somber halo
#

no prob

unkempt rock
#

hi

boreal umbra
#

Here's something I was thinking about. My understanding is that Python lists do some work under the hood so that they're arrays with O(1) operations, but if you end up needing more space, it does a resize operation, which I assume is O(n)

#

I don't know what logic it uses to decide when to resize. But if you're doing a list comprehension, and the length of the iterable you're using is known, does the interpreter allocate an array of that size?

north root
#

i don't think so since you can use if and else in list comprehensions

raven ridge
boreal umbra
#

@raven ridge thank you ๐Ÿ˜„

raven ridge
#

Detecting the size to avoid reallocations, that is.

willow shore
#

I've seen good numbers on preallocating to the length you need first

#

if I remember right I think that's also how C# treats List<> under the hood (doubling array size every time the limit is hit)

unkempt rock
#

In python, is it really more popular to use naming conventions such as variable_name more than variableName ?

flat gazelle
#

yes

stable grail
#

yes its part of the python naming guidelines @unkempt rock

#

!pep 8

fallen slateBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

pastel crest
#

which is the best program to create games

gloomy rain
#

@pastel crest This channel is for discussions of the Python language. Try #game-development.

potent shell
#

hey guys can anyone tell me where I can learn python web development???

wide shuttle
#

Corey Schafer has nice tutorial series on Django and Flask. The Django documentation also has a really nice tutorial to get you started.

#

However, this isn't really a topic for this channel; this channel is for discussing Python, the langauge, itself. Things like PEPs, the future of the language, and the implementation

potent shell
#

oh k got it!

meager trellis
#

Is there a python version manager similar to nvm ?

twilit garnet
#

perhaps pyenv?

#

@meager trellis

rapid haven
#

is there any good tutorial video on python database?

meager trellis
#

perhaps pyenv?
@twilit garnet so do people use pyenv together with virtualenv or pipenv for environment management?

sacred tinsel
#

pipenv is a popular choice, it integrates with pyenv well

#

there is also a plugin for pyenv called pyenv-virtualenv

#

it extends pyenv for virtualenv management if you prefer to do it manually

hardy belfry
#

Hello, I'm still in the process of learning Python. Can someone explain what a trailing comma does? Does it just force in a list to be printed horizontal rather than vertical?

true hollow
#

I think you should go to a help channel because I don't know the answer to that and I don't think people will expect your question here @hardy belfry

hardy belfry
#

sure, thanks. i thought it was a lot more simple than that

sacred tinsel
#

actually I think it'd be ok to have this conversation here

#

a trailing comma is necessary if you want to create a tuple with 1 element

#
>>> 1
1
>>> (1)
1
>>> 1,
(1,)
#

otherwise, it's not necessary, and has no effect on the code's behaviour (unless I'm missing some other case), but some prefer it for various reasons

#

if you have a vertical list, like so:

listy = [
  1,
  2
]

and I want to add another element, I have to make changes on 2 lines

#

with a trailing comma:

listy = [
  1,
  2,
]

you only need to change one line - the one you add

#

which makes for a nicer git diff, and it's also harder to accidentally forget to put the comma there (although that will usually be caught by your editor)

#

@rapid haven

is there any good tutorial video on python database?
we have a topic channel for #databases if you haven't noticed it yet

true hollow
#

@hardy belfry hey, actually kwzrd answered your question here

hardy belfry
#

ty! so i was just trying to find the difference between python 2 and python 3 with the trailing comma in regards to a print statement. So i figured out that in Python 2. x, a trailing , in a print statement prevents a new line to be emitted. In Python 3. x, use print("Hi", end="") to achieve the same effect

rapid haven
#

sorry i haven't noticed

sacred tinsel
#

oh right, @hardy belfry , that's a little bit different

#

I never used py2 so I'm not sure what the behaviour of the print statement (was it a stament? I think it was) there was

hardy belfry
#

no worries! Im learning through codecademy but only py2 is available but im also following along via ph3 via pycharm and found a handful of differences. just trying to work them all out ๐Ÿ™‚

#

(by available, i mean free haha)

flat gazelle
#

!resources

fallen slateBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

flat gazelle
#

do not make things more difficult on you by following a py2 tutorial

hardy belfry
#

i actually dont mind the challenge! and i like the completeiong circle in codeacademy. afterwards i might actually pay for the pro once i finish

#

im already too far invested to switch it up atm XD

full jay
#

It's not about the challenge aspect, it's more that there's no real reason to have to learn anything in the Python 2 style unless you plan on working on or maintaining legacy codebases

gray mirage
#

It is, quite honestly, a bit of a waste of time to do python 2 and then go ahead and do python 3 after

#

unless you really need that python 2 expertise

hardy belfry
#

I just like to know both for my own personal development

#

no other reason lol

full jay
#

Suit yourself

#

Not like I can claim that I've never researched something out of sheer curiosity rather than usefulness

#

In fact that's.... pretty much all of my research, come to think of it

hardy belfry
#

haha, yea i get that

rigid hazel
#

guys i have question for python

#

im new to python but i think this is v simple for u guys

#

can?its like v basic but i dont undertsand

shy vine
rigid hazel
#

okay ..sorry

toxic fractal
#

im having problem in installing of object detection api?? can u guys resolve this issue

gloomy rain
toxic fractal
#

sorry

gloomy rain
#

No worries.

unkempt rock
#

I am new here, Can anybody suggest where to start python learning?

narrow kettle
#

!resources

fallen slateBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

unkempt rock
#

Anything else plz...

narrow kettle
#

? i mean what else do you want that isnt covered by that page?

unkempt rock
#

Can u suggest me a book? :(

flat gazelle
#

there are books at that link

unkempt rock
#

pydistrong thx :)

narrow kettle
rigid hazel
#

whats a metasyntatic

coral birch
#

Does anyone have a principled opinion about relative vs. absolute imports in Python3? Now that implicit imports are gone, is it only a matter of taste, or is there a good reason to standardize my codebase on one or the other?

gray mirage
#

I think it depends on the context you expect your code to be running in

#

With a normal library then absolute imports are likely going to be king

#

But if you have, for example, a set of django apps, you might decide to move one or rename it

#

In that case you probably want relative imports

#

It's all about whether you expect things to be moved and how you expect to refer to your packages

coral birch
#

Right now it's a two level package.module setup with one package and a few dozen modules.

gray mirage
#

Absolute sounds fine

coral birch
#

Yeah, I don't expect the package name to ever change

gray mirage
#

I'd say absolute will be easier to read in most cases

coral birch
#

Thanks!

gray mirage
#

Discord, stop being bad, jeez

#

Failed sends everywhere

#

Anyway hopefully that helps

coral birch
#

I was getting some, too. And yes, it does.

gray mirage
#

There are situations where absolute imports don't work very well and that's where you resort to relative

placid wasp
#

What about python for competitive programming?

flat gazelle
#

it is possible, but some competitions require better performance than default python can give

rich wharf
#

one of my favorite constructs in Python is kwargs

#

I don't see it in many other languages and it is extremely helpful

#

It can make code so much more readable

gray mirage
#

kotlin calls them "named arguments"

#

they are pretty handy basically everywhere I've seen them

rich wharf
#

I haven't used kotlin so I'm not sure about it

#

but yeah they are, and they can make code so much more readable

flat gazelle
#

yeah, quite the rare feature. some modern languages do have them

rich wharf
#

but they are really helpful

#

especially when you need plenty of (optional) arguments

flat gazelle
#

pony I think as well, and probably rust

rich wharf
#

I'm planning to use them in my GUI lib

#

Kwargs are useful

#

Another place I find them useful is libs like discord.py

#

You can have optional kwargs when initializing for example an embed to specify extra details

flat gazelle
#

well, java deals with the plenty of optional args problem with builder/params objects

var obj = new Builder()
    .width(10)
    .height(20)
    .color(WHITE)
    .build();
```but it is a lot more boilerplate than what kwargs do
rich wharf
#

also, that gives me a question

#

are methods that return self with calls good practice?

#

self.do_thing(1, 2, x = 1, y = 2).do_another(1, 2, y = 3, z = 4).done()

#

or should you use some alternative

elder kiln
#

I have a function that runs a series of simulations for some models in another file. It returns partial output at the time that I keyboard interrupt it. Is there any way, through process or multiprocess module, to send a KeyBoardInterrupt signal to that function while it is running, and recieve the output in a different file? Specifically, I'm writing a unit test to see if the simulation actually returns partial results, but am not very familiar with process or multiprocess modules (not sure if I should be in help or not, seems a bit more advanced)

rich wharf
flat gazelle
#

in python, it feels out of place imo. Python does not like long expressions and the nice form of

obj
  .action()
  .action()
  .done()
```is not possible in python without some ugly parentheses or whatever
rich wharf
#

This isn't the right channel for that

real lake
#

Does anyone know c++, I need your help

rich wharf
#

@real lake this isn't the right channel for that, sorry

#

@flat gazelle I guess that's reasonable

grave jolt
#

Kwargs allow for a more immutable interface.

flat gazelle
#

as compared to what?

covert cape
#

hey, is the flow of execution (is that what it is called) for when you define classes the same as how it is when you define functions? (as in they start execution only when they're called)

flat gazelle
#

classes are initialized at import time. So

class U:
    print('1')
    def __init__(self):
        print('3')
print('2')
U()
```would print 

1
2
3

rich wharf
#

@covert cape the class body is immediately evaluated, like @flat gazelle 's example demonstrates

#

however the methods inside of it are only evaluated when called, like any other function

covert cape
#

oh okay thanks

wide shuttle
#

Basically, what happens is that this part:

    def __init__(self):
        print('3')

creates a function object just as if you've defined a function outside of a class body

#

The class attribute, U.__init__, will be assigned to the function object

#

And, just like another function object, it actually needs to be called to "do" something

#

And the function object we've assigned U.__init__ to automatically gets called during the object creation process to initialize it after __new__ created it

covert cape
#

okay that makes a lot of sense. thanks for the detailed answer ๐Ÿ˜„

shy nebula
#

how long will it on average take for a person who has never coded before (scratch doesn't count lol) to learn python? or at least understand it enough to make small projects

radiant fulcrum
#

not long

flat gazelle
#

depends on the person, but small projects are 1-4 weeks from what I hear.

full jay
#

Actually Scratch counts more than you might think

flat gazelle
#

scratch does absolutely count, missed that

full jay
#

One of the biggest hurdles in getting into programming can be understanding how to handle the logic flows

flat gazelle
#

ye, if you can use scratch, you have one of the most difficult parts done

shy nebula
#

oh, okay! :)

full jay
#

It's hard to give a proper time estimate, though. Everyone learns differently and at different paces.

shy nebula
#

yeh

full jay
#

If you haven't already, you can check out the various resources we have on our site

#

!resources

fallen slateBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

shy nebula
#

thx

full jay
#

Any time

unkempt rock
#

Is an indent equal to 4 spaces? or is 4 spaces smaller

flat gazelle
#

as per PEP8, indents should be 4 spaces

unkempt rock
#

sorry, as in when you click tab is that 4 spaces

wide shuttle
#

Hey @restive herald, this channel is not a help channel, but rather a channel to discuss Python itself

#

We do have a lot of help channels

meager trellis
#

@unkempt rock a tab is not 4 spaces.. itโ€™s a tab, which can be represented by as many spaces as the user wants.. usually two or 4.

gray mirage
#

It depends on the editor, I think is the answer they're looking for

#

Any decent Python editor will convert tab keypresses to four spaces.

unkempt rock
#

Thats what I figured, thanks

final whale
#

Is there a fast way to directly get the C source of builtins ? I'm kind of lost when browsing around the github repo ^^"

wide shuttle
#

Not that I know of. I usually use an external search engine, like google, as it typically takes me to the right spot

#

The GitHub search feature always returns dozens of hits with the right one buried on page 8

#

There is a structure to the directories as well, obviously

lean walrus
#

Anyone think python's going to still be a widely used thing in 5-10 years? I'm just wondering if it's worth learning it extensively, since there are other lanuages like GoLang that promise to be better in some way or other and may overtake python at some point..

flat gazelle
#

Python is most likely not going away that soon. There is a lot of code in python and the language has uses for which it is a very good choice, e.g. scientific computations, backend webdev, automation

lean walrus
#

Yeah I guess the number of systems built on it is an argument in its favour... thing is that all systems get upgraded eventually, and in python's use cases for data science type stuff it might not be that difficult to replace

languid cloak
#

Python is the GOD in AI, so I don't think it will go away

lean walrus
#

'data science type stuff' meaning AI

#

For now, yup. But as algorithms get more demanding and more computational power is needed and datasets grow larger there'll be a hard limit eventually

languid cloak
#

The future is gonna be all about AI

lean walrus
#

And quantum computers are slightly problematic for AI as well. They are definitely replacing classical programming for most AI in my opinion, once they get powerful enough

languid cloak
#

@lean walrus true

flat gazelle
#

well, COBOL is still in use. And you can always glue fast code together with python

lean walrus
#

Thing about COBOL is it's mostly used for very important data storage-and-handling mainframes and business programs... python can be replaced more easily since most of the AI parameters can carry over to an algorithm in a different language

#

I mean, not considering only AI. The same thing applies to most of the data science it's used for

flat gazelle
#

true enough, but there is no real reason to replace python, it does the job quite well. I do await the day python gets replaced though, because improvement over python sounds like quite the nice language to use

languid cloak
#

Python and C are basically the core of programming (i think)

lean walrus
#

Haha, yep. The thing that most concerns me is speed though... GoLang is apparently 15-30 times faster than python which is really not a small number

languid cloak
#

true

lean walrus
#

Obviously python programs will be hugely optimised but a lot of time goes into that which doesn't need to do so with go

languid cloak
#

Go is so fast

flat gazelle
#

yeah, but golang is not python

languid cloak
#

of course

#

i think python is older than golang

flat gazelle
#

yes, python is quite old

languid cloak
#

C is the oldest

#

i think

flat gazelle
#

not even close

twilit garnet
#

no it's not

flat gazelle
#

C is the oldest major lang

languid cloak
#

C was made in 1960, or something like that

twilit garnet
#

it wasn't even 1970

languid cloak
#

1972

twilit garnet
#

yeah

flat gazelle
#

C was made from B, which came from BCPL

languid cloak
#

Fortran is the oldest

twilit garnet
#

still not really.

#

but definitely getting there.

flat gazelle
#

LISP came up 1958, and LISP dialects are still around and quite good. FORTRAN is also quite old and has a lot of matrix multiplication code

fossil pumice
#

listen, we're not gonna discuss which programming languages are the oldest in this channel

#

cut that out

twilit garnet
#

oh oops

#

sorry

languid cloak
#

frotran was made in 1957

lean walrus
languid cloak
#

fortran*

#

sorry

#

sorrrrrrrrrrrrrrrrrrrrrrrrrrry!

fossil pumice
#

as for the speed, Python has gotten quite a bit faster in the past decade. It does this by outsourcing tasks that are performance critical to C extensions. For example, in python 3, several features of the standard library have been C-extensionified to improve performance over python 2.

in big data and data science, most of the major frameworks also rely heavily on C.

#

but in enterprice, usually Python isn't used in performance-critical contexts.

#

and it doesn't need to be.

languid cloak
#

I definitly think python is faster than C

lean walrus
#

Eventually it's got to hit a roof though, and that's not great for machine learning

full jay
#

Faster regarding development time, yes

twilit garnet
#

pure python can be hundreds of times slower than C in execution

full jay
#

Regarding actual running time....

flat gazelle
#

no language is consistently, demostrably faster than C for equivalent code

languid cloak
#

Oh Python was made in 1989!

fossil pumice
#

C is very fast.

twilit garnet
#

isn't rust pretty competetive though?

flat gazelle
#

Zig comes close with bitcode and LTO

full jay
#

First time I've heard of Zig

fossil pumice
#

so when people say that Python is slow, they're not necessarily wrong, but they are often misunderstanding what a major part C plays in CPython, and what the ramifications of that really are.

languid cloak
#

fortran and C are the fastest since they are the oldest(i think)

full jay
#

@twilit garnet Yes and no. Rust has a slight disadvantage because it does some checks at runtime

#

But it's certainly speedy

#

@languid cloak Age has nothing to do with speed.

languid cloak
#

rust is fast

#

@full jay yes

flat gazelle
#

interestingly, regexes in LISP are pretty much always faster than in C, because they get compiled to LISP code at compile/runtime (depending on the compiler). And C does not have those metaprogramming capabilities

full jay
#

It's the level at which they interact with the computer and how much overhead it takes

languid cloak
#

truw

#

true*

wide shuttle
#

For me, personally, when analyzing my data in a non-automated way (e.g., for research purposes), the combination of writing my analysis in a high-level language (like R and Python) that then call on C/Fortran to do the computations has always been the fatest.

ebon fox
#

Fortran is consistently demonstrably faster than C.

wide shuttle
#

No way I'm writing my analysis in Fortran/C/C++ directly.

flat gazelle
#

for heavy math yes, sometimes. Not for everything though

full jay
#

Yeah, and that's very important to remember

languid cloak
#

C is one of the easiest programming languages to learn, atleast to me

fossil pumice
#

exactly. what you make up in performance speed, you lose in development speed

languid cloak
#

yes

full jay
#

It's sometimes worth eating the performance a bit so that you don't have a miserable time writing the code

wide shuttle
#

Python or R make it easy: You can add your logic line-by-line, quickly try out a function with different parameters, and you don't have to recompile each time.

flat gazelle
#

I do wonder which language will be the one that manages to get a proper inferring typesystem to work in imperative code

twilit garnet
#

the C syntax is relatively simple but learning to use it properly and safely takes a long time and a lot of practice

fossil pumice
#

and it's not just about development speed either, but about morale and keeping programmers motivated so they will continue to be productive.

wide shuttle
#

And when it comes to the number crunching, they speak to C or Fortran for me.

flat gazelle
#

and use it to optimize memory

ebon fox
#

I mean there is no reason to choose one and dismiss the other. Different tasks call for different languages. One of the most beautiful usecases of Python is as the glue that can piece together code from other languages at will.

full jay
#

Unless it's Java

#

(I'm kidding half kidding)

flat gazelle
#

there is a lot of merit in having a single language in the entire codebase

gray mirage
flat gazelle
#

easier to hire for for one

languid cloak
#

Java is harder than Python

flat gazelle
#

as a language no, as an ecosystem, yes

gray mirage
#

It's a lot more verbose than python

#

and a lot of people suck at maven, which doesn't help

ebon fox
#

Yes, and that's exactly why Python is so great as an adhesive. You never even have to peek at any of the code behind the scenes.

gray mirage
#

Pretty much, yeah

languid cloak
#

i think javascript is also fast?!

full jay
#

Maven just does not feel intuitive

gray mirage
#

You can write useful code without worrying about the underlying tech in some cases

wide shuttle
languid cloak
#

yes

full jay
#

Fair point

wide shuttle
#

We're basically having a general chat about programming languages at this point

languid cloak
ebon fox
#

I'm surprised there's no programming languages channel

languid cloak
#

what do you mean

#

wdym

wide shuttle
#

Yes, it's meant to discuss the Python programming language itself, from a higher level perspective; it's not a general chat

ebon fox
#

To discuss programming languages in general.

flat gazelle
#

offtopic

languid cloak
#

now what are we doing, we're still not discussing Python?

#

no we're not

twilit garnet
#

there was a general programming languages channel a couple years ago. could ask about it in #community-meta @ebon fox

ebon fox
#

@twilit garnet ty

languid cloak
#

I was so happy the first time I did this

#
    import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("Game")

run = True
while run:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run = False


pygame.quit()
#

sorry it's a little disoriented!

#

Bye!

ebon fox
#

๐Ÿ‘

wide shuttle
#

@fossil pumice This is everything

#

!e

class Descriptor:
    def __get__(self, instance, owner):
        print("__get__ was called with:", instance, owner, end="\n\n")

    def __set__(self, instance, value):
        print("__set__ was called with:", instance, value, end="\n\n")

    def __delete__(self, instance):
        print("__delete__ was called with:", instance, end="\n\n")

    def __set_name__(self, owner, name):
        print("__set_name__ got called with:", owner, name, end="\n\n")


print("First assigning the descriptor calls `__set_name__`")
class Foo:
    attribute = Descriptor()

    def __init__(self):
        print("Accessing the attribute calls __get__")
        self.attribute
        print("Assigning to the attribute calls __set__")
        self.attribute = "Hello!"
        print("Deleting the attribute calls __delete__")
        del self.attribute


f = Foo()
fallen slateBOT
#

@wide shuttle :white_check_mark: Your eval job has completed with return code 0.

001 | First assigning the descriptor calls `__set_name__`
002 | __set_name__ got called with: <class '__main__.Foo'> attribute
003 | 
004 | Accessing the attribute calls __get__
005 | __get__ was called with: <__main__.Foo object at 0x7f68d2891f10> <class '__main__.Foo'>
006 | 
007 | Assigning to the attribute calls __set__
008 | __set__ was called with: <__main__.Foo object at 0x7f68d2891f10> Hello!
009 | 
010 | Deleting the attribute calls __delete__
011 | __delete__ was called with: <__main__.Foo object at 0x7f68d2891f10>
wide shuttle
#

Maybe @worldly venture also wants to see it

worldly venture
#

oh this is very cool

wide shuttle
#

So, in this case, you're accessing a class attribute directly on the instance with self.attribute

#

And that's the important bit here

#

That's also why accessing a method, like self.method() works

#

Methods are not instance attributes, but rather regular function objects assinged to class attributes

#

And because you access them on the instance, the __get__ method of the function object gets called, with the instance as an argument

#

And __get__ then takes care of creating that boundmethod where the instance is automatically passed as the first argument for self

fossil pumice
#

shit, that's a really subtle but crucial distinction.

#

thanks for sharing

wide shuttle
#

There are few more subtleties

#

Like what happens when you assign to an attribute when a __set__ isn't implemented

#

The last (?) Chapter of the first edition of fluent Python explains it well

#

Haven't read the second edition yet, but it's probably in there

radiant fulcrum
#

Right question for y'all,
In the process of building a cache db / caching system.

I have two possible designs ig you could call them?

  1. Micro cache with the system directly imported into python which gives obviously a massive decrease in latency and allows the cache control of any python objects or c type objects, the issue comes with global cache, being a per instance type of deal you don't want to be having multiple cache DBs per process that has to store individual info (more aimed at websites and load balancing) now the best way I could think of with this is linking each process with its own global memory alloc, the downside to this is complexity.

  2. move it to a server type of deal but loose support of python future objects etc... But you intern gain it being more likely to not cause a memory issue (tho unlikely) and easy global cache. This does however also increase latency

worldly hedge
#

@radiant fulcrum Will you be serving the 1st option through a single process or using docker/kubernetes?

radiant fulcrum
#

In theory it could be either

#

In reality idek

worldly hedge
#

Well, imo, if you decide to do the first one, you improve end user experience but you also need to dedicate too much time on it

radiant fulcrum
#

What I don't wanna do is rely on K8s and docker to fix/mask any memory leaks when the system is being designed to control its own memory allocation and use of there of

worldly hedge
#

If it is a personal project, I would go with it

#

Running a complex caching system requires some sort of clustering

#

more aimed at websites and load balancing
This is done through multiple processes

radiant fulcrum
#

I know

#

Hence the need for a global linking of some sort

worldly hedge
#

Also, linking a process with an individual global memory block can drink up your memory very fast

#

I think you should dynamically allocate memory using a session method.

radiant fulcrum
#

Hmmm

#

That would be an idea

worldly hedge
#

Take care for back pressure as well, if you are using a server complex you also need a way to distribute memory access in order to offload pressure

#

I had made a system 3-4 months ago which used the same principle as yours

#

I ended up making it work only to realize that each time the server distributed the processes weirdly

#

Causing an overload in the first server, slowing down everything and inadvertently crashing

unkempt rock
#

@unkempt rock

#

wsh zinc

#

genre jsuis un dรฉveloppeur moi

#

yey

fossil pumice
#

@unkempt rock this community is English only.

#

and this channel is for discussing the Python language, not for pinging people to tell them you're a developer.

radiant fulcrum
#

I'm just tryna think about some of the best methods of inter process communicating

#

Like sockets, webserver idk

worldly hedge
#

if you are talking about simple communication and not huge data load, you can use sockets

radiant fulcrum
#

That's the issue tho because in theory it could be massive data loads at time

worldly hedge
#

Could you give me an example?

radiant fulcrum
#

Altho unlikely I can't rule it out as I want to make it as scalable as possible

worldly hedge
#

You can manage huge data loads with threading but then again it also comes down to memory management

#

Because although threading can prove to be a solution for socket load balancing, it can get overloaded really fast

unkempt rock
#

@fossil pumice ok friend

radiant fulcrum
#

So would you still role with sockets then in the end?

#

Or are there any other methods that might be better

worldly hedge
#

I am trying to think

fossil pumice
#

you guys are also a bit off-topic here, tbh, although I appreciate the conversation you're having.

worldly hedge
#

If you have constant data streaming up and down, sockets are the way to go since they allow you for practically no latency between the time data gets sent and the time it gets received as the original handshake remains the same

#

@fossil pumice where should we move?

#

@radiant fulcrum Are you using an async approach to your inner communication methods so far?

fossil pumice
#

eh, fuck it. hang out.

#

I don't have a great alternative

radiant fulcrum
#

It'll have to be sync tbh

worldly hedge
#

haha thanks

radiant fulcrum
#

Altho I could possibly run the server as async

#

Any nodes or processes would end up being sync cuz flask

worldly hedge
#

Could you give me a bit of heads up in regards of your server architecture?

radiant fulcrum
#

Not exactly, what I want is to be able to have this as a module, building alot of the caching and memory management in Rust for the low level control and python as the interface per say

#

My use case would be a flask site

#

But Id like to be able to have it as dynamic as possible

worldly hedge
#

hmm

radiant fulcrum
#

I think sockets might be the best way to go

worldly hedge
#

Well, sockets are the way to go

unkempt rock
#

@unkempt rock hi

worldly hedge
#

I don't see a reason why you wouldn't make it on async

radiant fulcrum
#

Cuz flask

#

If it's a flask servers it's sync

worldly hedge
#

I know

#

idk

#

I wouldn't use flask if I had heavy shit on my service

#

I usually make everything on aiohttp.

#

I have module-d all the basic things so every time I have to build something new I mostly replace and call functions

#

The thing is that threading with sockets is good but it can limit you

placid wasp
#

Where can i learn python for competitive programming?

worldly hedge
#

Since in requests everything gets serialized, even if you use sockets data will travel linearly meaning that when there is big data load you will still experience latency, using an async approach you can literally have multiple socket instances run concurrently in different threads, never waiting for the response to get delivered, in other words, awaiting it

radiant fulcrum
#

Yh

#

I might have a look at quart if I remember the name right

worldly hedge
#

Yea

#

I don't think you want a module-specific approach

#

Rather, a loop specific approach

#

Your whole module could run as a coroutine for something else

#

I can see a use case for this beyond web

radiant fulcrum
#

Only thing I could see being an issue is how df I would have async rust interact with async python

#

Tho that does sound rather fun to try lol

worldly hedge
#

oof rust is nice

radiant fulcrum
#

I'm using for its Zero garbage collector system

#

And the sheer amount of control you get

worldly hedge
#

Rust is fast and efficient I like it

radiant fulcrum
#

Yr

#

Ye*

worldly hedge
#

In reality, if you ever want to build fast caching systems C++ is the way to go, but this is out of the context of this conversation

#

Since python literally will bottleneck you at some point

radiant fulcrum
#

I mean rust has plenty of control for stuff like that but then we're getting more offtopic lol

#

And yeah

worldly hedge
#

haha yea

#

I like the idea of your module though

radiant fulcrum
#

Python will hit the cap long before the dB system

worldly hedge
#

Might as well use it

#

And that is all due to that damn gil

radiant fulcrum
#

I'll work on some designs tomorrow ig, sleep time now tho

worldly hedge
#

Goodnight, thanks for the chat!

unkempt rock
#

@unkempt rock hi men

nimble quail
#

Hey, I was just wondering, what are some good Python libraries on GitHub to contribute to?

charred wagon
magic python
#

How come a pandas column will tab complete, but a dictionary won't?

df = pd.DataFrame(dict(blah = [1,2,3]))

df['b<tab>

vs

d = {'something' : [1,2,3]}

d['som<tab>
#

the first one will complete to blah, whereas the second won't do anything

charred wagon
#

Wrong channel. You can ask in #tools-and-devops for things related to your code editor.

magic python
#

@charred wagon i disagree

#

I'm not talking about code editor specific, this seems to be general, and I assumed that it was a language thing

charred wagon
#

No. If you write code in notepad on Windows, for example, then nothing will tab complete.

#

It's behaviour of your editor

magic python
#

ok - what tab completes for dictionaries then?

charred wagon
#

Also, read the channel topic up top

magic python
#

just pycharm?

#

i thought there was something with the language that provided a hook or something, rather than it being an editor thing

charred wagon
#

Yea, pretty sure it's just Pycharm's code completion feature

magic python
#

hrm ok, i've never used pycharm... I just noticed when using notebooks and stuff, and wondered if there was something underlying that was enabling completion in pandas stuff but not dictionaries

#

i don't really care about editors here, but if that's all it is then fair enough

grizzled vigil
#

@magic python IIRC, tab completion for dictionaries was just recently implemented for the IDLE (built-in lightweight IDE for Python) not too long ago. I don't remember if it's in 3.8 or upcoming in 3.9 though.

#

But I'm sure you can find the feature in some other IDEs and editor plugins as well

fierce geode
#

anyone have a good numpy tutorial?

#

I couldn't find a playlist by corey scafer on it

grizzled vigil
#

@fierce geode This channel is intended to specifically focus on the discussion of the Python language itself, rather than more general questions. But to point you in the right direction, I'd start with https://numpy.org/devdocs/user/quickstart.html if you're not specifically looking for just video tutorials.

fierce geode
#

got it, sorry bout that and thank you for the recommendation

unkempt rock
#

Hello I have so much money in the world right now, what's the best book for python I could look for on Amazon to buy for myself? For someone who has no experience at all.

slim island
#

Best is very dependant on you. However, Automate the Boring Stuff is pretty highly reccomended

#

(but is also available for free)

tender kite
#

are there header files in python where i can keep all my list instantiations and import stuff in one file?

#

kind of like C programming

flat gazelle
#

not really, you can make a dedicated module for it, but generally, you just import things you need in the file into the file

tender kite
#

ok

dusty haven
#

Its not uncommon to have a module dedicated to constants if you're program uses a bunch

unkempt rock
#

Is this possible to make addition of int and string work in python?
I would like to work like that:

int=112
string="call "
result=string+int #call 112
wide shuttle
#

In this case, you want to create a string, right?

unkempt rock
#

yes, overload it somehow

wide shuttle
#

You'll either need to create a string from the int or use string interpolation

#

!e print("call " + str(112))

fallen slateBOT
#

@wide shuttle :white_check_mark: Your eval job has completed with return code 0.

call 112
unkempt rock
#

is this possible to do that without str() function?

wide shuttle
#

Python does not do those kind of implicit conversions that javascript does, but you can use string interpolation, if you want

unkempt rock
#

to declare somewhere operation of addition for int and string

#

in C++ we can overload operations in classes, in python int and string are classes, can we overload addition here?

wide shuttle
#

Not really, because the behavior of the operation is defined for a specific type/class. That means you'd have to create a custom string or int class that knows how to do that. In general, though, the philosophy is that types shouldn't change or be guessed unexpectedly.

#

String interpolation is commonly used for this, though, as that always creates the string representation of the object for you

#

!e

number = 112
text = f"call {number}"
print(text)
fallen slateBOT
#

@wide shuttle :white_check_mark: Your eval job has completed with return code 0.

call 112
wide shuttle
#

So, there's no easy overloading; it would have to be a subclass with a custom __add__ method

unkempt rock
#

Okay, I was just curious if it's possible ;D
Thanks for pointing out string interpolation, I didn't know about that

flat gazelle
#

you can do it if you are willing to mess with implementation details in CPython. Not viable in actual code though

novel bison
#

Does the bot take inputs?

fallen slateBOT
#

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

slim island
#

no @novel bison

novel bison
#

alright! || @half rampart ||

flat gazelle
#

you can redirect stdin though

slim island
#

I just noticed the channel - this isn't the right channel at all really

torpid plinth
#

is there a recursion limit on calling a function

radiant fulcrum
#

there is a recursion depth limit if thats what you mean

sacred tinsel
#

yeah, there's a limit on the stack size

radiant fulcrum
#

you can change it irrc

#

iirc*

sacred tinsel
#

you can set it to a higher value but you probably shouldn't

#
>>> def func(): func()
... 
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in func
  File "<stdin>", line 1, in func
  File "<stdin>", line 1, in func
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
>>> 
>>> import sys
>>> 
>>> sys.setrecursionlimit(100000000)
>>> 
>>> func()
Segmentation fault (core dumped)
radiant fulcrum
#

What ive noticed is that Docker compose will not have Cython extensions at all

#

it just straight up ignores their existance and believes theyre not there

cloud crypt
#

@sacred tinsel ```python
from typing import NoReturn

* you can't just recurse! *

def func() -> NoReturn:
# haha try func() except func() go brrrr
try:
func()
except RecursionError:
func()```

shut anchor
#

You know what would be really handy? OrderedDicts with index/key modes in its methods.

#

Instead of it just being keys.

sacred tinsel
#

can you show an example of what that would be like?

shut anchor
#

od.__getitem__(5, mode='index')

sacred tinsel
#

so what does that give you?

cloud crypt
#

od.get(5, mode="index")

#

Dicts are dicts, after all, though?

#

wouldn't it be O(n)

peak spoke
#

How would you pass the mode to getitem?

cloud crypt
#

there would be no way to call it via od[...]

shut anchor
#

Yeah. It'd be a default thing in the def of mode='key'.

#

But at least you could do it in the dunders.

cloud crypt
#

@sacred tinsel ah also powers of 10 are not fun, I just straight up sys.setrecursionlimit(2**31 - 1). What makes me wonder is why they used signed long for that

peak spoke
#

really shouldn't be in the dunder if the access point would be calling it directly

cloud crypt
#

that's what I thought

clear ocean
#

Whats the function that controls the behaviour of getting items? e.g dict[key]

#

I can never remember what its called

cloud crypt
#

__getitem__

clear ocean
#

thanks ๐Ÿ‘Œ

#

i'll note that down

cloud crypt
#

I donโ€™t really like how it passes one argument tbh

shut anchor
#

od.byindex[n] maybe, then.

cloud crypt
#

oof

#

why wouldn't it be .byindex(n) then

shut anchor
#

Setters and getters.

cloud crypt
#

oh fair

shut anchor
#

I mean, OrderedDicts, great. So they're ordered, but then no clear way to refer to the entries by index.

#

Am I right in thinking that's a bit of an obvious thing to have missing, or...?

gloomy rain
#
from collections import OrderedDict
d = OrderedDict()
d["foo"] = 1
d["bar"] = 2
d["baz"] = 3
d.keys()
['foo', 'bar', 'baz']
d.keys()[1]
'bar'
``` ?
shut anchor
#

Sure, but what about sets and gets and all of that?

full jay
#

He's literally setting and getting

shut anchor
#

Sorry. Um.

gloomy rain
#

d[d.keys()[1]] = "bazinga"

#

The value of ordered dicts is not being able to reference items by index, it's that you have a guaranteed key order that you can rely on.

cloud crypt
#

what is bazinga pithink

gloomy rain
#

I needed another dummy string, lol

#

foo bar baz bazinga

shut anchor
#

Big Bang Theory sitcom reference.

#

"d[d.keys()[1]]" ๐Ÿ‘

cloud crypt
#

aka d.values()[1] because you are not assigning

#

@gloomy rain I just use lemon ๐Ÿ‹

fossil pumice
#

I use firedog

#

and watercat

#

and if at that point I need more I just randomly concat an element and an animal

flat gazelle
#

I just do letters at that point or, if applicable, meaningful names

torpid plinth
#

guys wanna see somthing funny

#

this is my teachers code :

#
from random import *
a=[0,0,0,0,0]
v=[0,0,0,0,0]
a[0]=1+randrange(5)
t=0
j=0
def fp():
    for k in range(5):
        v[k]=a[k]
def regen():
    global a,t,j
    x=int(1+randrange(5))
       for r in range(t):
        if a[r]==x:
            regen()
    a[t]=x
    j+=1
    if j==4:
        fp()
    ml()
def ml():
    global t      
    if t<4 and j<5:
        t+=1
        regen()    
ml()           
print("printing now") 
for k in range(5):
        print("values"+ str(v[k]))
#

and here is my code:

#
import random
arrayy = []
for i in range(10):
    n=random.randint(0,4)
    if r not in arrayy:
        arrayy.append(r)
print(arrayy)

#

both do the same

#

funny how python condenses that much logic

grave jolt
#

I guess the teacher was implementing some random number generation algorithm.

#

Linear congruential generator -- I think that's what it's called

torpid plinth
#

so basicly, this is was very complex for the class. i needed a way to make a array and fill it with random numbers but the numbers cannot repeat.

#

my friend uses alot of the with, and, or keywords

flat gazelle
#

!d random.sample

fallen slateBOT
#
random.sample(population, k)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be [hashable](../glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

To choose a sample from a range of integers, use a [`range()`](stdtypes.html#range "range") object as an argument. This is especially fast and space efficient for sampling from a large population: `sample(range(10000000), k=60)`.... [read more](https://docs.python.org/3/library/random.html#random.sample)
flat gazelle
#

should be helpful

torpid plinth
#

wasnt asking for help

gloomy rain
#

@torpid plinth Your code will give an array of variable length.

torpid plinth
#

more flexable

gloomy rain
#

Since you only generate 10 numbers and skip duplicates.

torpid plinth
#

isnt it a programmers goal to write code in the least amount of lines

radiant fulcrum
#

no?

gloomy rain
#

Less code is often more readable, but not necessarily.

flat gazelle
#

no, the goal is to write code that is most readable

gloomy rain
#

But your code also needs to work.

radiant fulcrum
#

less lines != better programmer

torpid plinth
#

well if you can condense code without losing your desired output

radiant fulcrum
#

i mean no

torpid plinth
#

then its good enough

#

ik what != is

radiant fulcrum
#

that doesnt make you a better programmer

gloomy rain
#

!= is the "not equal" operator

flat gazelle
#

correct > fast enough > readable > consistent > idiomatic > fast

torpid plinth
#

so a person who writes 50 lines of code to write a program and a person writes the exact same program in 25 lines of code

radiant fulcrum
#

that depends massivley

torpid plinth
#

you are telling me that programmer isnt writing more effciant code?

#

less ram useage?

molten onyx
#

those 50 lines might be needed for efficiency reasons

flat gazelle
radiant fulcrum
#

less lines != less ram

molten onyx
#

you can't judge code based on line count

torpid plinth
#
import random


listt = []

for i in range(10):
    r=random.randint(0,4)
    if r not in listt:
        listt.append(r)
    
flat gazelle
#

LOC is entirely worthless as a metric

torpid plinth
#

run that

molten onyx
radiant fulcrum
#

probably

gloomy rain
#

!e ```py
import random

listt = []

for i in range(10):
r=random.randint(0,4)
if r not in listt:
listt.append(r)
print(listt)

fallen slateBOT
#

@gloomy rain :white_check_mark: Your eval job has completed with return code 0.

[2, 3, 0, 4, 1]
torpid plinth
#

ยฏ_(ใƒ„)_/ยฏ

#

run my teachers code?

#

pls?

gloomy rain
#

I find it very unlikely you want to generate an arbitrary-size list.

radiant fulcrum
#

It tends to be a bad idea to believe less lines = better programming

flat gazelle
#
In [91]: import random

In [92]: random.sample(range(5), 5)
Out[92]: [3, 2, 0, 1, 4]
torpid plinth
#

nice mate

flat gazelle
#

definitely, less code does not always mean better code.

torpid plinth
#

i said efficient

radiant fulcrum
#

still doesnt apply

gloomy rain
#

Writing a correct program in the fewest lines or characters possible is called "code golfing", and optimally golfed programs are useless in the real world, since they are completely unreadable.

flat gazelle
#

still not applicable. The most efficient strlen implementation in C++ is much longer than the trivial one.

#

in python, efficiency is often not that important, but just writing less code can be less efficient

gloomy rain
#

And yes, highly performant code is very often much longer than the solution that's quickest to write.

flat gazelle
#

for example

def splitby(items, pred):
    r = []
    l = []
    for i in items:
        if pred(i):
            r.append(i)
        else:
            l.append(i)
    return r, l
def splitby(items, pred):
    return [i for i in items if pred(i)], [i for i in items if not pred(i)]
```which one of these is more efficient?
torpid plinth
#

my mind wont be changed, i consider "golf programming" better. i suggest you move on from this lol

radiant fulcrum
#

then that will limit you later in life lol

gloomy rain
#

Recursive implementations of sorting algorithms are often small and neat-looking, but not efficient due to stack allocation overhead (among other things)

flat gazelle
#

you are demostably wrong

torpid plinth
#

ive written 400+ lines of code just to show couple of sprites on the screen

#

its not always golf programming

radiant fulcrum
#

400 lines for some sprites seems like it could be optimised

torpid plinth
#

lmao bro make your mind up xd

radiant fulcrum
#

but Optimised does not mean golf programming

torpid plinth
#

making a board game so the sprites have to be generated with certain rules

flat gazelle
#

there is a sweet spot between too much code and too little code

torpid plinth
#

so the spawing algorithm is very long

flat gazelle
#

you want to hit it

torpid plinth
#

yeye defo

radiant fulcrum
#

Writing code is not about Line count, The less lines does not mean the faster the code, I would rather write more lines but have it be more optimised than some code which is few lines but slower

gloomy rain
#

Minimizing boilerplate and unnecessary complexity is a good rule of thumb, and it often results in less code, it's just not an absolute rule.

flat gazelle
#
for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
```is by no means good code, despite being really short
gloomy rain
#

Sometimes clarity requires you to add more code and longer names.

radiant fulcrum
#

does the !e import this easter egg work with snek box?

flat gazelle
#

I think so

torpid plinth
#

what about gui based programs. no one is going to look at the code, thier only concern is if the code works . besides im graded on the algorithms and flowcharts,ipo charts nd stuff

radiant fulcrum
#

why would a Gui program be an exception

torpid plinth
#

hurting my brain

flat gazelle
#

you can write clean GUI code, but GUI code is one of the hardest things to write nicely

#

because there is just a lot of logic involved

torpid plinth
#

lot of x and y

gloomy rain
#

@torpid plinth Developers will read the code when they maintain it.

#

Maybe the GUI program needs new features. Maybe you discover bugs that needs to be fixed.

torpid plinth
#

ive commented everything

flat gazelle
#

comments do not save bad code

gloomy rain
#

Comments aren't necessarily always a good thing.

radiant fulcrum
#

comments can be bad

gloomy rain
#

Comments can easily get outdated and misleading.

radiant fulcrum
gloomy rain
#

And then they make things worse than if there had been no comments at all.

flat gazelle
#

putting a lipstick on a potato still just makes it a colorful potato

gloomy rain
#

It's always best to write code that is self-explanatory, so you don't need to add comments.

torpid plinth
#

my brain. idk about you bois but i don't write incorrect code. and i don't forget to change comments. maybe you guys need to remember to update your comments then you'll realize why they are there

radiant fulcrum
gloomy rain
#

@torpid plinth Just to give you fair warning, we don't tolerate trolling on this server, so be careful with how you conduct yourself here.

#

If you have any interest in sticking around, that is.

radiant fulcrum
#

Ngl, There's a diffrence between being a good programmer who writes good code and someone who wont listen to outside input

torpid plinth
#

so me giving you a peice of advice or suggestion is trolling?

radiant fulcrum
#

Bad attitude to have if you ever intend to work in a dev team lmao

gloomy rain
#

@torpid plinth I'm saying that I will use my best judgment to determine whether your advice is given in good faith or if you're trying to be provocative intentionally. And if I decide that on the latter, I won't hesitate to throw you out. So just keep that in mind when you speak.

torpid plinth
#

im not questioning the mods but im just saying. If thats trolling then...ive been trolled as well

gloomy rain
#

I suggest you err on the side of caution and try to be friendly.

flat gazelle
#

writing consistently correct code is quite difficult, especially in python, as the language has very little safety net to fall back on.

torpid plinth
#

ill forget i typed in this chat if you the same

unkempt rock
#

Imagine someone writing a comment about what a print statement would wrote ๐Ÿคฃ

#

Write*

#

Iโ€™ve seen that before, itโ€™s horrific

radiant fulcrum
#

Tho whole Uggly potato with lipstick situation again lul

unkempt rock
#

This statement write Hi in the terminal

print(โ€˜Hiโ€™)

#

๐Ÿ˜ฌ

#

Yikes

flat gazelle
#

comments are needed very rarely. They are nice to link related outside docs/specs, especially in code that cannot be readable due to outside constraints (seldom a thing in python code specifically). But in python, you can get really far by just naming things well

steep harness
#

how can i append a int to a list

flat gazelle
#

some_list.append(8)

gilded tree
#
listvar.append(intvar)
steep harness
gray mirage
#

No, list.append(int)

unkempt rock
#

yes

gray mirage
#

Not int.append(list)

steep harness
#

ohh stupid me

#

ues know i konw

#

i se fuck me

undone hare
#

And you shouldn't name it list, because you won't be able to do list() anymore

gray mirage
#

This is the wrong channel for help requests btw

steep harness
unkempt rock
#

So basically what i want to do is make a python script that will change a value in a script (it will ask the user what to change it to) and then pack the file to a .exe , would really appreciate someone helping me ๐Ÿ™‚

steep harness
#

make it in tkinter that will be cool

tacit sinew
#

Is it possible to change the color of functions in python?

#

For example the function eval it shows in dark blue.. I don't like that..

steep harness
#

no i dont think so mabye there is a package for it

gray mirage
#

The interpreter doesn't have anything to do with that, it's down to your editor

#

Most of them do have a colour scheme option. You could ask about that in #tools-and-devops

flat widget
#

hei guys ! sorry for disturbing. I am trying to :

-import clr
-clr.AddReference('System.Management')

but console says: AttributeError: module 'clr' has no attribute 'AddReference'

p.s: computer says no xD

gray mirage
flat widget
#

em oh, thanks ๐Ÿ™‚ iยดll check there

clever escarp
#

@tacit sinew that highlighting is done via whatever editor you are using. I would recommend just trying to get used to it, because it is widely accepted; the built-in functions being highlighted is something other people would expect to see when reading your code. It definitely is possible to change, but as how you do it would depend on the editor you're using, you'll want to ask in #tools-and-devops if you need help with it

tacit sinew
#

@clever escarp In Darcula theme it looks purple it is much better than in Light theme where it shows it Dark blue almost black..

gray mirage
#

Try the material theme plugin, there's a nice light theme in it

boreal umbra
#

I don't want to divert the discussion going on in general, but I'm struggling to understand what Anaconda is for.

flat gazelle
#

anaconda is a distribution of python meant for scientific stuff. It comes with various packages (numpy, ...)built in, as well as spyder and similar tooling. Certain packages are also mainly on conda and getting them from PyPi is impossible/difficult

#

it is still CPython though, but I am not sure if it is the same builds as the ones on the python website

boreal umbra
#

It seems like it's just an extra layer of complexity around basic Python functionality.

flat gazelle
#

it is convenient if you actually have a use for all the conda packages, and it does have its own venv manager thing, but for most users, it is as you said, just more complexity.
I have used it to install some packages which I could not get from pypi and the alternative would be build from source

boreal umbra
#

if there are packages that you can't get any way other than conda, then isn't the only benefit of conda for non-conda users that it solves problems that conda itself introduces?

somber halo
#

I've used to use anaconda quite a bit but to be honest I don't really use it nowadays

#

The last time I really used it was through its miniconda thingy

flat gazelle
#

there are some differences between the 2 which makes conda the better choice for certain packages, especially those which are in C/C++/R mainly with thin python wrappers, or even with no relation to python whatsoever

boreal umbra
#

ah

flat gazelle
#

also, it mainly distributes binaries, and as such does not need a compiler, unlike pip sometimes

final whale
#

What are use cases for :

class Foo:
  bar: int = 5
``` vs
```py
class Foo:
  def __init__(self, *args, **kwargs):
    self.bar: int = 5
flat gazelle
#

It can be useful with metaprogramming, and sometimes you want static attributes that are common to the whole class

final whale
#

makes sense, thank you captain

charred wagon
#

If you want to autospec the class for tests, it won't be able to see instance attributes unless you pass an instance as the spec. Creating an instance can have side effects that would be undesirable, so you can use class attributes to avoid creating an instance.

grave jolt
#

It's also useful for dataclasses, since they generate __init__ based on these attributes.

#

And other things like sqlalchemy and wtforms use this information, I believe

#

Or more esoteric stuff (yes, I will post it again!)

#

!e

from "#esoteric-python" import SumType # the implementation is too long to fit here, so
# I used gzip+base85 to post it here, but I replaced that with an import statement

class MaybeInt(SumType):
    Just.of( int )
    Nothing.of( () )

print(MaybeInt)

x = MaybeInt.Just(42)
print(f"{x=}, {type(x)=}, {MaybeInt.Just}")
assert isinstance(x, int) and isinstance(x, MaybeInt) and isinstance(x, MaybeInt.Just) and not isinstance(x, MaybeInt.Nothing)

n = MaybeInt.Nothing()
print(f"{n=}, {type(n)=}, {MaybeInt.Nothing}")
assert isinstance(n, tuple) and isinstance(n, MaybeInt) and isinstance(n, MaybeInt.Nothing) and not isinstance(n, MaybeInt.Just)
fallen slateBOT
#

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

001 | MaybeInt {'Just': <:MaybeInt.Just :: <class 'int'>>, 'Nothing': <:MaybeInt.Nothing :: ()>}
002 | x=42, type(x)=embellished('MaybeInt.Just', <class 'int'>), MaybeInt.Just
003 | n=(), type(n)=embellished('MaybeInt.Nothing', ()), MaybeInt.Nothing