#internals-and-peps
1 messages ยท Page 43 of 1
nevermind, let's get back on topic
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
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
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
print("hello, programmers!")
hi anyone online
it's pretty accessible with nvda, the screen reader
can anyone guide me where can i ask question in this server about our python code?
Reminder that this is not the channel for such discussion. Either #python-discussion , an off-topic channel or if you have a question you need help with see #โ๏ฝhow-to-get-help
@languid dagger thanks man i really appreciate it
Is that a good way of swapping variables or is it a no no
var1, var2 = var2, var1
It is a good good ๐
I was expecting you to get some funny itertools stuff to swap them haha
Is it better than using a temporary variable?
Yup
I think (a, b) = (b, a) could be a bit faster
tuples don't come into play anywhere with those swaps
ye, the bytecode is optimized for that. But for more complex swaps, it does just build tuples
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.
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 :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
It does everything on the stack without creating a new tuple.
Can I post here 30 lines of code do demonstrate my problem? Or do you suggest to write it in help channel?
a help channel would be more suited
you could use semantic versioning and compare major versions
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
is python 2 worth learning ?
no
Nope.
is it good practice to rely on Nonetype being falsy instead of checking identity ?
Depends on the data you can receive
Checking identity is never going to hurt if you expect None though
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
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.
!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
:incoming_envelope: :ok_hand: applied mute to @daring lark until 2020-05-26 05:44 (11 hours and 59 minutes).
I'm not too sure about the channel, but has anyone ever used a phylogenetic tree in order to reduce repetitions when making dataclasses ?
What is the best way to learn Python?
The best way depends on you - but this isn't the right channel, I'll write a longer reply in #python-discussion
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
If I'm using the switch statement in python, do the cases have to be numerical?
like so if its checking multiple conditions
uh. there isnt switch in python
oh, i was looking at this
oh using a dictionary
Any hashable value works.
so then should I just stick to repeated elif statements?
if i want an easier way to implement what a switch statement does?
well, if you scroll down, there are the dict variants
Any reason to use obj.__class__ over type(obj) ?
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
very short one, I explain why I prefer type(x).name vs x.class.name. thanks to @alikus for the question!
previous video about @property: https://youtu.be/orp6bhe4i00
playlist: https://www.youtube.com/playlist?list=PLWBKAf81pmOaP9naRiNAqug6EBnkPakvY
==========
...
this video explains it quite well
just finished watching it, that was super interesting
so type(x) doesn't just call _class_
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
well a given value might be assigned to more than one variable
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.
that wouldn't matter
can somebody help me with homework ;/
this is not the right channel for that, #โ๏ฝhow-to-get-help
ok
>>> 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
Neat function
does that count?
does that get __name__ too
>>> def f():pass
...
>>> [*names(f)]
['f']
>>>```
can you match it with the locals name
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
yea i get that
i think im gonna have it loop backwards thru the frames locals to look for a binding
wait, then it will have val as the name
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
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
so should different functions be put in different python files? im new
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
import
ah ok
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
okay i get it now
thank you
on e more Q
so in main.py
i could call a function that is in file.py?
the normal way
you would do it like that
i don't think you have to iterate through a dict if you already have the name
lol
def obj(name):
frame = inspect.currentframe()
while (frame := frame.f_back):
if name in frame.f_locals:
return frame.f_locals[name]``` there
random questions. Are "while" statements loops and "if" statements arent, correct?
Correct
ty @frozen solar !
#bot-commands
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.
this isn't the channel for it, you can try a normal help channel
@deft pagoda Thanks!
@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?
@sonic mortar Great, thanks! New and trying to get a sense of the flow. Being patient ๐
That's a yes. Only use free Help channels to ask your questions
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).
you can probably do with contextlib.redirect_stdout and stderr and have the bot send msgs into a specific channel
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 ?
#โ๏ฝhow-to-get-help wrong channel
too hards to undesrtand
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
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Ope
Anyway, the section on fstrings (https://docs.python.org/3/reference/lexical_analysis.html#f-strings) and the section on the format language (https://docs.python.org/3/library/string.html#formatspec) don't seem to document this behavior
I might just be blind though
How'd I use redirect_stdout to see what's in terminal?
@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
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
Oh I have a good cheat sheet/site for that
Pretty much anything marked as the New Style can be used with f-strings
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
we should i use f stings
It's neat but should be used sparingly. It can get a bit cluttered and hard to read after a while
i meant when
Any time you want to toss a value into a string
any better alternatives
So when you would do something to concatenate a string or what have you
fstrings are the best atm, they are essentially str.format, but faster
Yep
The only weakness is that you can't easily make template strings from them
But that's a very minor point
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
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
I like python's implementation of them the most, probably
JS's string interpolation is pretty much the same
though I do like how they're done in swift
What's the style in Swift?
"text \(variable)"
That feels clunky to me
It does look odd at times, yeah, but it's an interesting choice imo
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
Yeah, exactly, and there's no need to put a symbol before the string either
Or like in JS's case, use backticks
Or wait, was that another one...
So many languages
raku has a nice system
It's backticks as quotes and then ${expr} in JS, yeah
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
That's probably why curly braces are so widely used when it comes to formatting/interpolation
True
can anyone think of some pros/cons of using dataclasses.make_dataclass instead of collections.namedtuple?
How to do a probibility in python ? I want that thing happen with a probaility of 0.2 for exemple
You can weighted randoms with the random module
how
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
@flat gazelle
https://docs.python.org/3/library/random.html#random.choices Choices gives you the option to weight things
Though if you just want 20% chance for sth to happen, you can do
if random.random() < 0.2:...
Although I'd probably do it with randint() because my brain doesn't like floats
Aaah nice
my brain doesn't like how floats are represented in binary
Same
Right
what do you guys recon is the best method of getting the programs current Ram and CPU usage
Yeah
idk but not the channel to rlly discuss that, they'll probably explain it
Depends on the os CF8
โ silenced current channel for 6 minute(s).
!unsilence
โ unsilenced current channel.
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
I'd probably look into psutil or something like that because it'll be os dependent
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
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
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.
wouldnt os do that?
(self, nums: List[int]) -> int:
what does this do
# 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)}')```
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.
So there's a discrepancy between the actual filesize and how much memory is taken up on the drive.
What do you mean?
Why would you care in discrepancy between the two? What do you hope to gather with the data?
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
Compression will only help if you combine files into single zip
I'm also interested in seeing it.
Thanks
Steve, you will need to pull allocation size from drive and do the math yourself, Windows apparently does it for you in explorer
Important lesson learnt now about Rust builds for python
if you build it in debug mode it will fail to compile
i have no idea why
but its a thing
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?
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
ah ok
what does the second parameter of print do (also under the for loop)
the ", urlToOpen"
Sorry. I can't walk you through the very basics of python. I recommend you to do a beginners guide
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
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@meager meadow print can take any number of arguments
yea im doing atbs rn, just never used print(something, somethingelse)
Ah I getcha
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.```
coolcool
what is the difference between an Array and a List?
Which array? array.array, bytearray, numpy.ndarray?
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)
does python have an array data type?
The python list is implemented using an array
There is also bytearray and the C interop arrays
https://docs.python.org/3/library/array.html
@somber halo i didn't understant how to create an array (i'm noob sorry for being so dumb)
let me see
What is your goal. You probably want a list
i'm learning c# now and i want to know the differences between an array and a list
the practical differences
Off-topic channels
There are three off-topic channels:
โข #ot0-psvmโs-eternal-disapproval
โข #ot1-perplexing-regexing
โข #ot2-never-nesterโs-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
temp_array = array('d', [1., 2., 3.])
sorry, you need to import the array package
oh ok
from array import array
temp_array = array('d', [1., 2., 3.])
no reason in particular
xD
just to signal these are intended to be doubles
either way
In Python, the use of array isn't that common.
right.
hence why you declare the datatype when you initialize your array
I mean, it could be infered automatically hypothetically
ok thank you
no prob
hi
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?
i don't think so since you can use if and else in list comprehensions
@boreal umbra - https://www.interviewcake.com/concept/java/dynamic-array-amortized-analysis explains how amortized constant time dynamic array appends work in general. Resizes will just happen whenever it runs out of room.
@raven ridge thank you ๐
and https://github.com/python/cpython/blob/master/Objects/listobject.c#L52 is the code that does it ๐
@boreal umbra - and, it appears the answer to your other question is "no" - https://bugs.python.org/issue36551 is a discussion about trying to do just that.
Detecting the size to avoid reallocations, that is.
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)
In python, is it really more popular to use naming conventions such as variable_name more than variableName ?
yes
which is the best program to create games
@pastel crest This channel is for discussions of the Python language. Try #game-development.
hey guys can anyone tell me where I can learn python web development???
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
oh k got it!
Is there a python version manager similar to nvm ?
is there any good tutorial video on python database?
perhaps
pyenv?
@twilit garnet so do people use pyenv together with virtualenv or pipenv for environment management?
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
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?
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
sure, thanks. i thought it was a lot more simple than that
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
@hardy belfry hey, actually kwzrd answered your question here
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
sorry i haven't noticed
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
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)
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
do not make things more difficult on you by following a py2 tutorial
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
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
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
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
haha, yea i get that
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
Please see: #โ๏ฝhow-to-get-help
okay ..sorry
im having problem in installing of object detection api?? can u guys resolve this issue
@toxic fractal This channel is for discussion about the Python language. Please check #โ๏ฝhow-to-get-help for help with specific issues.
sorry
No worries.
I am new here, Can anybody suggest where to start python learning?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Anything else plz...
? i mean what else do you want that isnt covered by that page?
Can u suggest me a book? :(
there are books at that link
thx :)
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
whats a metasyntatic
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?
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
Right now it's a two level package.module setup with one package and a few dozen modules.
Absolute sounds fine
Yeah, I don't expect the package name to ever change
I'd say absolute will be easier to read in most cases
Thanks!
I was getting some, too. And yes, it does.
There are situations where absolute imports don't work very well and that's where you resort to relative
What about python for competitive programming?
it is possible, but some competitions require better performance than default python can give
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
kotlin calls them "named arguments"
they are pretty handy basically everywhere I've seen them
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
yeah, quite the rare feature. some modern languages do have them
pony I think as well, and probably rust
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
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
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
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)
@elder kiln if it's advanced, I highly recommend #โ๏ฝhow-to-get-help
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
This isn't the right channel for that
Does anyone know c++, I need your help
@real lake this isn't the right channel for that, sorry
@flat gazelle I guess that's reasonable
Kwargs allow for a more immutable interface.
as compared to what?
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)
classes are initialized at import time. So
class U:
print('1')
def __init__(self):
print('3')
print('2')
U()
```would print
1
2
3
@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
oh okay thanks
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
okay that makes a lot of sense. thanks for the detailed answer ๐
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
not long
depends on the person, but small projects are 1-4 weeks from what I hear.
Actually Scratch counts more than you might think
scratch does absolutely count, missed that
One of the biggest hurdles in getting into programming can be understanding how to handle the logic flows
ye, if you can use scratch, you have one of the most difficult parts done
oh, okay! :)
It's hard to give a proper time estimate, though. Everyone learns differently and at different paces.
yeh
If you haven't already, you can check out the various resources we have on our site
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thx
Any time
Is an indent equal to 4 spaces? or is 4 spaces smaller
as per PEP8, indents should be 4 spaces
sorry, as in when you click tab is that 4 spaces
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
@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.
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.
Thats what I figured, thanks
Is there a fast way to directly get the C source of builtins ? I'm kind of lost when browsing around the github repo ^^"
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
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..
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
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
Python is the GOD in AI, so I don't think it will go away
'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
The future is gonna be all about AI
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
@lean walrus true
well, COBOL is still in use. And you can always glue fast code together with python
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
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
Python and C are basically the core of programming (i think)
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
true
Obviously python programs will be hugely optimised but a lot of time goes into that which doesn't need to do so with go
Go is so fast
yeah, but golang is not python
yes, python is quite old
not even close
no it's not
C is the oldest major lang
C was made in 1960, or something like that
it wasn't even 1970
1972
yeah
C was made from B, which came from BCPL
Fortran is the oldest
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
listen, we're not gonna discuss which programming languages are the oldest in this channel
cut that out
frotran was made in 1957
And my pattern-related suspicions are confirmed
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.
I definitly think python is faster than C
Eventually it's got to hit a roof though, and that's not great for machine learning
Faster regarding development time, yes
pure python can be hundreds of times slower than C in execution
Regarding actual running time....
no language is consistently, demostrably faster than C for equivalent code
Oh Python was made in 1989!
C is very fast.
isn't rust pretty competetive though?
Zig comes close with bitcode and LTO
First time I've heard of Zig
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.
fortran and C are the fastest since they are the oldest(i think)
@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.
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
It's the level at which they interact with the computer and how much overhead it takes
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.
Fortran is consistently demonstrably faster than C.
No way I'm writing my analysis in Fortran/C/C++ directly.
for heavy math yes, sometimes. Not for everything though
Yeah, and that's very important to remember
C is one of the easiest programming languages to learn, atleast to me
exactly. what you make up in performance speed, you lose in development speed
yes
It's sometimes worth eating the performance a bit so that you don't have a miserable time writing the code
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.
I do wonder which language will be the one that manages to get a proper inferring typesystem to work in imperative code
the C syntax is relatively simple but learning to use it properly and safely takes a long time and a lot of practice
and it's not just about development speed either, but about morale and keeping programmers motivated so they will continue to be productive.
And when it comes to the number crunching, they speak to C or Fortran for me.
and use it to optimize memory
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.
there is a lot of merit in having a single language in the entire codebase

easier to hire for for one
Java is harder than Python
as a language no, as an ecosystem, yes
It's a lot more verbose than python
and a lot of people suck at maven, which doesn't help
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.
Pretty much, yeah
i think javascript is also fast?!
Maven just does not feel intuitive
You can write useful code without worrying about the underlying tech in some cases
I think these type of conversations are more suited for #python-discussion.
yes
Fair point
We're basically having a general chat about programming languages at this point
it says #internals-and-peps
I'm surprised there's no programming languages channel
Yes, it's meant to discuss the Python programming language itself, from a higher level perspective; it's not a general chat
To discuss programming languages in general.
offtopic
there was a general programming languages channel a couple years ago. could ask about it in #community-meta @ebon fox
@twilit garnet ty
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!
๐
@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()
@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>
Maybe @worldly venture also wants to see it
oh this is very cool
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
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
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?
-
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.
-
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
@radiant fulcrum Will you be serving the 1st option through a single process or using docker/kubernetes?
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
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
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
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.
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 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.
I'm just tryna think about some of the best methods of inter process communicating
Like sockets, webserver idk
if you are talking about simple communication and not huge data load, you can use sockets
That's the issue tho because in theory it could be massive data loads at time
Could you give me an example?
Altho unlikely I can't rule it out as I want to make it as scalable as possible
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
@fossil pumice ok friend
So would you still role with sockets then in the end?
Or are there any other methods that might be better
I am trying to think
you guys are also a bit off-topic here, tbh, although I appreciate the conversation you're having.
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?
It'll have to be sync tbh
haha thanks
Altho I could possibly run the server as async
Any nodes or processes would end up being sync cuz flask
Could you give me a bit of heads up in regards of your server architecture?
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
hmm
I think sockets might be the best way to go
Well, sockets are the way to go
@unkempt rock hi
I don't see a reason why you wouldn't make it on async
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
Where can i learn python for competitive programming?
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
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
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
oof rust is nice
I'm using for its Zero garbage collector system
And the sheer amount of control you get
Rust is fast and efficient I like it
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
I mean rust has plenty of control for stuff like that but then we're getting more offtopic lol
And yeah
Python will hit the cap long before the dB system
I'll work on some designs tomorrow ig, sleep time now tho
Goodnight, thanks for the chat!
@unkempt rock hi men
Hey, I was just wondering, what are some good Python libraries on GitHub to contribute to?
This isn't the right channel. Your question is better for #python-discussion
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
Wrong channel. You can ask in #tools-and-devops for things related to your code editor.
@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
No. If you write code in notepad on Windows, for example, then nothing will tab complete.
It's behaviour of your editor
ok - what tab completes for dictionaries then?
Also, read the channel topic up top
just pycharm?
i thought there was something with the language that provided a hook or something, rather than it being an editor thing
Yea, pretty sure it's just Pycharm's code completion feature
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
@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
anyone have a good numpy tutorial?
I couldn't find a playlist by corey scafer on it
@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.
got it, sorry bout that and thank you for the recommendation
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.

Best is very dependant on you. However, Automate the Boring Stuff is pretty highly reccomended
(but is also available for free)
if you have any more questions - try #python-discussion , this isn't the right channel
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
not really, you can make a dedicated module for it, but generally, you just import things you need in the file into the file
ok
Its not uncommon to have a module dedicated to constants if you're program uses a bunch
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
In this case, you want to create a string, right?
yes, overload it somehow
You'll either need to create a string from the int or use string interpolation
!e print("call " + str(112))
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
call 112
is this possible to do that without str() function?
Python does not do those kind of implicit conversions that javascript does, but you can use string interpolation, if you want
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?
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)
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
call 112
So, there's no easy overloading; it would have to be a subclass with a custom __add__ method
Okay, I was just curious if it's possible ;D
Thanks for pointing out string interpolation, I didn't know about that
you can do it if you are willing to mess with implementation details in CPython. Not viable in actual code though
You are not allowed to use that command here. Please use the #bot-commands channel instead.
no @novel bison
alright! || @half rampart ||
you can redirect stdin though
I just noticed the channel - this isn't the right channel at all really
is there a recursion limit on calling a function
there is a recursion depth limit if thats what you mean
yeah, there's a limit on the stack size
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)
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
@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()```
You know what would be really handy? OrderedDicts with index/key modes in its methods.
Instead of it just being keys.
can you show an example of what that would be like?
od.__getitem__(5, mode='index')
so what does that give you?
How would you pass the mode to getitem?
there would be no way to call it via od[...]
Yeah. It'd be a default thing in the def of mode='key'.
But at least you could do it in the dunders.
@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
really shouldn't be in the dunder if the access point would be calling it directly
that's what I thought
Whats the function that controls the behaviour of getting items? e.g dict[key]
I can never remember what its called
__getitem__
I donโt really like how it passes one argument tbh
od.byindex[n] maybe, then.
Setters and getters.
oh fair
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...?
from collections import OrderedDict
d = OrderedDict()
d["foo"] = 1
d["bar"] = 2
d["baz"] = 3
d.keys()
['foo', 'bar', 'baz']
d.keys()[1]
'bar'
``` ?
Sure, but what about sets and gets and all of that?
He's literally setting and getting
Sorry. Um.
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.
what is bazinga 
I use firedog
and watercat
and if at that point I need more I just randomly concat an element and an animal
I just do letters at that point or, if applicable, meaningful names
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
I guess the teacher was implementing some random number generation algorithm.
Linear congruential generator -- I think that's what it's called
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
!d random.sample
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)
should be helpful
wasnt asking for help
@torpid plinth Your code will give an array of variable length.
more flexable
Since you only generate 10 numbers and skip duplicates.
isnt it a programmers goal to write code in the least amount of lines
no?
Less code is often more readable, but not necessarily.
no, the goal is to write code that is most readable
But your code also needs to work.
less lines != better programmer
well if you can condense code without losing your desired output
i mean no
that doesnt make you a better programmer
!= is the "not equal" operator
correct > fast enough > readable > consistent > idiomatic > fast
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
that depends massivley
you are telling me that programmer isnt writing more effciant code?
less ram useage?
those 50 lines might be needed for efficiency reasons
this is a single line of code
https://hastebin.com/feziyirage.py
less lines != less ram
you can't judge code based on line count
import random
listt = []
for i in range(10):
r=random.randint(0,4)
if r not in listt:
listt.append(r)
LOC is entirely worthless as a metric
run that
Anyway I feel like this belongs in #python-discussion not here
probably
!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)
@gloomy rain :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 0, 4, 1]
I find it very unlikely you want to generate an arbitrary-size list.
It tends to be a bad idea to believe less lines = better programming
In [91]: import random
In [92]: random.sample(range(5), 5)
Out[92]: [3, 2, 0, 1, 4]
nice mate
definitely, less code does not always mean better code.
i said efficient
still doesnt apply
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.
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
And yes, highly performant code is very often much longer than the solution that's quickest to write.
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?
my mind wont be changed, i consider "golf programming" better. i suggest you move on from this lol
then that will limit you later in life lol
Recursive implementations of sorting algorithms are often small and neat-looking, but not efficient due to stack allocation overhead (among other things)
you are demostably wrong
ive written 400+ lines of code just to show couple of sprites on the screen
its not always golf programming
400 lines for some sprites seems like it could be optimised
lmao bro make your mind up xd
but Optimised does not mean golf programming
making a board game so the sprites have to be generated with certain rules
there is a sweet spot between too much code and too little code
so the spawing algorithm is very long
you want to hit it
yeye defo
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
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.
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
Sometimes clarity requires you to add more code and longer names.
does the !e import this easter egg work with snek box?
I think so
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
why would a Gui program be an exception
hurting my brain
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
lot of x and y
@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.
ive commented everything
comments do not save bad code
Comments aren't necessarily always a good thing.
comments can be bad
Comments can easily get outdated and misleading.
And then they make things worse than if there had been no comments at all.
putting a lipstick on a potato still just makes it a colorful potato
It's always best to write code that is self-explanatory, so you don't need to add comments.
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

@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.
Ngl, There's a diffrence between being a good programmer who writes good code and someone who wont listen to outside input
so me giving you a peice of advice or suggestion is trolling?
Bad attitude to have if you ever intend to work in a dev team lmao
@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.
im not questioning the mods but im just saying. If thats trolling then...ive been trolled as well
I suggest you err on the side of caution and try to be friendly.
writing consistently correct code is quite difficult, especially in python, as the language has very little safety net to fall back on.
ill forget i typed in this chat if you the same
Imagine someone writing a comment about what a print statement would wrote ๐คฃ
Write*
Iโve seen that before, itโs horrific
Tho whole Uggly potato with lipstick situation again lul
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
how can i append a int to a list
some_list.append(8)
listvar.append(intvar)
No, list.append(int)
yes
Not int.append(list)
And you shouldn't name it list, because you won't be able to do list() anymore
This is the wrong channel for help requests btw
See #โ๏ฝhow-to-get-help in future
but know this gets op
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 ๐
make it in tkinter that will be cool
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..
no i dont think so mabye there is a package for it
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
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
Have you had a look at #โ๏ฝhow-to-get-help?
em oh, thanks ๐ iยดll check there
@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
@clever escarp In Darcula theme it looks purple it is much better than in Light theme where it shows it Dark blue almost black..
Try the material theme plugin, there's a nice light theme in it
I don't want to divert the discussion going on in general, but I'm struggling to understand what Anaconda is for.
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
It seems like it's just an extra layer of complexity around basic Python functionality.
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
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?
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
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
ah
also, it mainly distributes binaries, and as such does not need a compiler, unlike pip sometimes
What are use cases for :
class Foo:
bar: int = 5
``` vs
```py
class Foo:
def __init__(self, *args, **kwargs):
self.bar: int = 5
It can be useful with metaprogramming, and sometimes you want static attributes that are common to the whole class
makes sense, thank you captain
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.
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)
@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