« first day (3121 days earlier)      last day (1828 days later) » 

2:01 PM
*be
 
Just got my pycon ticket for Oktober in Berlin =D Anyone else planning to go to that one?
 
@PeterVaro I knew you cared :p
 
A recent question asks: how do I convert a jpg to a csv? No additional details are given.
 
Just rename the file and let the magic happen?
 
hehe
 
2:13 PM
Some OPs have such great faith in our crystal ball abilities that it makes me want to cry
 
It is oddly satfisying though when you see a post and think: "I bet what they're really trying to ask is..." - don't have to time to request clarification - then later come back to it and it's "yup... I was right..." :p
 
I can't decide whether the question is "how do I extract the pixel values from this image and write them all in a human-readable csv?" or "how do I perform ultra-complicated computer vision on an image and get a result like 'subject: jellybeans (confidence 90%) \n total bean count: 36 (confidence 60%)`?"
I could write the answer to the former in one and a half minutes, but if I'm wrong about which question is being asked, then I'll get harangued about phd level topics that I have no knowledge of
 
umm... jeally beans.... licks lips
 
The jellybean standard test image looks pretty unappetizing to me, personally. Maybe it's because the table looks a little dingy.
It might be the lighting. When was this picture taken? It's almost Polaroid-like.
 
I'm going to sit here drooling over jellybelly.co.uk/flavours now...
 
2:23 PM
The ones in Kevin's image don't look very bean-shaped. But maybe that's the perspective.
 
bean there, done that
 
@PM2Ring it's all in the eating :)
 
Twist: the image is actually computer generated by a Deep Dream esque algorithm that has only read textual descriptions of jelly beans.
 
@Kevin that's be a great twist... and data needs to be extracted from that image to train other machines what jelly beans look like :p
and after a few generations - machines concept of what jelly beans look like is just chinese whispers... and then before you know it - everything tastes like chicken and we're wondering if it was the same cat or not...
 
Tastes like chicken? Called Soylent Green? Suspicious!
 
2:28 PM
@PeterVaro o/
 
@AnttiHaapala heya, old friend, how's it hanging there?
 
@PeterVaro winter is here... :D
 
@AnttiHaapala so I heard! (I have a finnish colleague now ;))
 
so we had nice +15C and then may day picnics were in a bit cooler weather and now this :d
fortunately I am in Helsinki today
 
Maybe that shape is less of a choking hazard for small children than the traditional shape, but it's hard to say without knowing the scale.
 
2:34 PM
the kidney-shape fits better in your nose
 
Today I am annoyed by message board threads like "what are some common 'facts' that are not actually true?" and half of the responses describe untrue facts, and the other half describe actually true facts which are the logical opposite of common non-facts. There is no way to distinguish between these two if you aren't already familiar with the non-fact.
Example: "if you get stabbed, leave the knife in". Does this mean "leaving the knife in is common advice but actually bad", or does it mean "pulling the knife out is common advice but actually you should leave it in"
 
If in doubt - compromise... pull it half way out? :p
 
What show was it where character A has been skewered by a sharp object, and character B pulls it out, and A says "actually you're supposed to leave it in", and B replies "Oh, sorry," and sticks the sharp object back in the wound
I want to say... Futurama
 
Sounds plausible...
 
2:54 PM
Any one have a quick and simple solution for this, I have log files that can look like this 'log.20190418.120020.txt' and 'log.20190418.txt' in the same dir. Im searching through them all and would like to extract the date out.. I was trying with datetime.strptime(date_time_str, '%m/%d/%Y') but have had no luck. Any ideas?
 
For one thing that looks more like YYYYMMDD to me than MMDDYYYY so I wouldn't expect that format string to work
 
@Kevin I would have thought those were skittles, TBH
 
Wait, copied the wrong strptime... I have this since there is no / in there. datetime.strptime(date_time_str, '%Y%m%d')
 
Looks like you want to be using re.search rather than strptime'ing....
 
@PeterVaro Finn colleague at T?
 
2:57 PM
Yeah, I was just about to suggest regex. Locate the first 8 consecutive digits, then strptime that.
 
@AnttiHaapala well, she is Customer Success TBF
:)
 
@PeterVaro actually I found her just by googling F T :D
google is eval
 
>>> import re
>>> import datetime
>>> test_cases = ['log.20190418.120020.txt', 'log.20190418.txt']
>>> [re.search("\d{8}", s).group(0) for s in test_cases]
['20190418', '20190418']
>>> [datetime.datetime.strptime(re.search("\d{8}", s).group(0),"%Y%m%d") for s in test_cases]
[datetime.datetime(2019, 4, 18, 0, 0), datetime.datetime(2019, 4, 18, 0, 0)]
 
You rock! Thanks!
Was just spinning that up now.
Regex is something I need to use more
 
@AnttiHaapala you followed my profile, realised where I work, searched for the company, went for the team page, searched for a finnish name?
 
3:04 PM
Hard mode: extract all numbers so that "log.20190418.txt" becomes datetime(2019, 4, 18, 0, 0) and "'log.20190418.120020.txt'" becomes datetime(2019, 4, 18, 12, 0, 20)
This ranges between "easy, if there are exactly two different kinds of filename" and "impossible, if we don't know anything about the possible kinds of filename"
 
@PeterVaro no. I went to your profile, realized where you work, went to Google, entered company name and an ethnicity/nationality adjective, hit search, open first search result.
it is too good :F
 
Hey all, I have a standard dictionary in python with just one key/value pair. I would like to assign a new value without having to type out the key name in my code i.e. I would like to reference it by some sort of numerical identifier, which is fine as there is only one key/value pair.

Do i have to use an OrderedDict for this?
 
@AnttiHaapala good stuff :)
 
@PeterVaro it was to l-i, and everyone lists the languages there.
 
@Andy how would you do that with OrderedDict?
As in, why do you think it would be easier
 
3:09 PM
@Andy list(dic.items())[0], or replace items with keys or values
 
@Andy you can get the only key wit next(iter({'a':5}))
 
Asking about OrderedDict makes sense if you assume that OrderedDict provides additional methods to allow interfacing with it via numerical indices. But it doesn't. This problem is just as difficult with OrderedDict as with regular dict.
 
or easy
 
Frustrating ambiguity in English that "X is as difficult as Y" can be interpreted to mean either "X and Y are equally difficult and they are both difficult" or "X and Y are equally difficult but I provide no information about their position on the ease/difficulty gradient"
 
Seriously I want to make a version of python where empty dictionary is {:} and empty set is {}
 
3:13 PM
ah ok
 
Is Simon trying to solve a non-existent problem here?
 
so to replace a value i have to reference the full key name? :S
actually i could use dict.keys() and then pass the value in as a variable
as each dict has only one key/value pair
thanks all
 
>>> d = {"foo": "bar"}
>>> d[next(iter(d.keys()))] = "narf"
>>> d
{'foo': 'narf'}
 
You aren't using Python 2, are you
 
no
@kevin awesome :)
thank you
 
3:17 PM
@Kevin d.keys() - really? :p
 
Obligatory disclaimer: if you later discover that you need to replace one of the keys of a dict that has more than one key, then you can't draw any conclusions about which key will get updated by my code, unless you're using a version of Python where dicts are ordered.
So, like... 3.6 and up. Somewhere around there.
@JonClements Hmm, don't really need that, do I
>>> d = {"foo": "bar"}
>>> d[next(iter(d))] = "narf"
>>> d
{'foo': 'narf'}
 
>>> d[[*d][0]] = 'narf'
Beauty
 
hole in one
 
haha... as long as there definitely is only ever 1 key and not millions :p
 
Obligatory grumble about how I loathe single item dicts...
 
3:25 PM
>>> d = {"foo": "bar"}
>>> dict.fromkeys(d, 'narf')
{'foo': 'narf'}
I win
God I'm good :D
 
except you don't just change a single item in the case of > 1 element, you basically alter the value of every key in the source dict... slight difference :)
but I do like that one if it's absolutely guaranteed there's only ever 1 (or no) keys :)
 
Yeah, that's the assumption
 
That's the winner then - for one key or empty dicts - that's nice... for > 1 dicts, different though... :p
 
I must admit that dict.fromkeys(d, 'narf') is cute.
 
I had a general question,
 
3:30 PM
Oops, I spent the last thirty minutes misunderstanding the increasingly irritated comments from an OP explaining that I completely missed the point of their question
 
I am a beginner to python! maybe < 2 years
 
oh hi there @Devesh - nice of you to pop in :)
 
Beware of doing stuff like dict.fromkeys(keyseq, []), though. ;)
 
when would be a good time to stop convoluting your code with dict/list comprehension
 
Hopefully my completely revised answer isn't also missing the point
 
3:31 PM
and start doing simple and readable loops
I am new to SO, and I see both types of answers being presented here
but somehow list comprehensions win, no matter how unreadable they are
 
@DeveshKumarSingh what do you mean by "convoluting" and "simple and readable loops" - list/dict-comps can be just as readable as multiply indented loops for instance..
 
its just that i need to learn more on how to use them >
I assume
 
Well, could you provide an example of what you mean maybe?
 
If you're asking "at what point in my development as a programmer should I stop using list comprehensions entirely?", never. List comprehensions are a language feature, not a crutch. If you're asking "at what level of complexity should a list comprehension be refactored into something more understandable?", that's something you develop an instinct for over time
 
3:33 PM
@DeveshKumarSingh 2 or 3 levels deep is about the limit. Rule of thumb: if it's slower for you to read the list comp than the traditional loop version, use traditional loops.
 
Okay I will ensure that I read complete sentences which can be comprehended completely, thanks @vaultah
 
I do think it's a problem when SO users upvote an unreadable list comprehension. I think they do it not because it's a good solution, but because they're dazzled by the apparent skill on display
Faced with incomprehensible code, you can either think "wow, what wizard wrote this?" or "wow, what fool wrote this?"
 
@DeveshKumarSingh The point to stop is when it convolutes code. You should not introduce anything that makes the code harder to understand if there's already a comprehensible solution. Several people on SO main try score imaginative points by cramming everything into a 1-liner, and several others are amused enough to upvotes it as clever
 
I think @Kevin put it quite well! A new user who just might be looking for something that works, and accepts and uses an unreadable list comprehension ends up doing more harm then good
Also I have seen a trend where these list comprehensions are almost never explained by the poster, and just put there, because they are all in a single line, whereas if you use traditional loops, you have space to explain your code inline, which makes it much cleaner to refer what is happening within the code!
 
Sure there's an explanation; "You can do this" :)
 
3:41 PM
SO answers can certainly be terse and cryptic and thus fall short of production-quality standards
 
@roganjosh *"Try this:"
 
This is a consequence of the race-to-answer-first incentive structure of the site
 
@DeveshKumarSingh you can put comments within list comprehension too.
 
@Devesh ahh was this inspired by the Q&A here?
 
yes, I have been too much into SO the past month, and this has been both a bane and a boon to me! By the time I am writing a traditional loop, 2/3 answers of list comprehension show up and are upvoted and accepted haha
 
3:43 PM
If your instincts tell you "I can't understand this list comp" or "I wish I had more space to put in some explanatory comments", then that's a perfectly acceptable reason to refactor into a proper loop
 
'cos as @Antti mentions, you can break a list comp over multilines as well, but don't have to necessarily do the full indentation...
 
yes, here if the OP could have just used a traditional structure, he would have never hit this!
 
flatten_matrix = [val
                  for sublist in matrix # iterate over the outer dimension
                  for val in sublist]   # iterate over the inner dimension
 
Damn @AnttiHaapala I didn't know we can do this, can the list comprehension be broken after any keyword, or maybe I can use line breaks \ in list comprehension
 
@AndrasDeak sure, I mean, by the very nature of comprehensive explanations means that they must vary based on the situation :)
 
3:45 PM
strangely, I'd probably find something such as:
result = [
    col if col > 5 else col + 2
    for row in matrix
    for col in row
    if something_else(col)
]
 
@DeveshKumarSingh within parentheses/brackets/braces you can break after any token
 
slightly easier to read that if that was written "traditionally"
 
And what takes the cake is when builtin functions like filter , map, zip etc take part in list comprehension, that it becomes another level of complex
 
What Kevin said. I often use list comps etc in my answers, but if the list comp version is too dense I'll post a more readable version in the main part of the answer, and put the super-condensed version as a postscript, and perhaps add a remark that the previous version is much more readable, and that the speed difference is probably marginal.
 
@Devesh generally there's not much need to use filter or map...
 
3:46 PM
That way, I'm giving a good answer, but may also pick up an extra upvote or 2 from the list comp groupies. Or downvotes from people who disapprove of that sort of thing. ;)
 
You forgot throwing itertools in the mix
 
sometimes I write [*map(foo, bar)] :P
shorter than [foo(i) for i in bar]
 
@roganjosh but that's generally doing something that the builtin syntax can't do easily :p - while basic ieration and pairing can be...
 
yes . I actually learned about itertools and builtin via stack overflow itself
it makes lot of complex data processing much more easier to break down, making python more functional programmesque and I kind of like that
 
There was one guy whose answers come straight to mind on this, but it's a name I'd only recognise on seeing it that did this to the n'th degree. I have nothing against itertools, but they'd cram it in with all of the aforementioned filter/map etc. and I had a real hard time following it
Scratch that, I remember the name. I haven't seen them for quite a while, actually
 
3:51 PM
@JonClements filter & map are ok, if their function arg is a builtin function, and tolerable if it's a Python function you need anyway. Using them with a lambda is madness. And slower than the equivalent listcomp or gen exp.
 
on prod level python are there good or bad practices against using itertools or builtins i rarely see them in prod code
 
If you don't see builtins in production code then I don't know what it is you're looking at tbh
 
builtins yes but itertools very rarely
 
@DeveshKumarSingh zip is pretty useful in list comps when you need to iterate over stuff in parallel. It's a standard Python idiom. But if you find it too hard to read, use zip in a traditional loop.
 
I actually worry that when I start writing code professionally, there will be dumb rules like "no itertools/functools", "no map/filter/zip", "no list comps", "no f-strings, use percent formatting", "no <this cute efficient trick>, use <this mess> instead"
 
3:58 PM
It's pretty hard to do much in Python without builtins, apart from trivial stuff. OTOH, it's unusual to use the builtins name explicitly.
 
@PM2Ring I think I possibly only use zip and things like map(int, something) these days... syntax wise you can make a generator for map, or make it a list-comp without having to worry about calling list on it... plus, [int(el) for el in something] allows room to easily do an if condition or calculation on the lhs than re-writing something that's written as: list(map(int, something))...
 
also this might be stupid @AnttiHaapala but is there a difference between using say list(map(lambda x:x**2, range(5))) or [*map(lambda x:x**2, range(5))]
essentially list(map(foo, bar)) or [*(map(foo, bar)]
 
Not stupid, and no
 
@DeveshKumarSingh list = [1,2,3]
 
Meh
Writing code so that you can be stupid elsewhere? :P
 
4:03 PM
I did not get you @AnttiHaapala your comment about list = [1, 2, 3]
 
Perhaps he's saying "list(map(foo, bar)) crashes if the variable name list was previously overwritten"
 
morning cabbage
 
@roganjosh breathes a sigh of relief... I normally get all the blame for itertools stuff :p
 
ohh, yes why will you ever use a reserved keyword as a variable
 
You shouldn't, but your clueless coworkers might
 
4:06 PM
It's not reserved and it's not a keyword
Very strictly speaking
 
@DeveshKumarSingh The 2nd one is microscopically faster, but they're both slower than [x**2 for x in range(5)] because they have to do a slow Python function call on each iteration. That's why I said before that using map or filter with a lambda is madness.
 
if that is out the window, that I haven't used list as a keyword, both are equivalent right!
 
Consult docs.python.org/3/reference/lexical_analysis.html#keywords for a list of actually reserved keywords. You can't overwrite these, even accidentally.
 
@Kevin Why did 3.x have to ruin the True, False = False, True fun! :p
 
4:09 PM
"""fun"""
 
@DeveshKumarSingh You can"t use a reserved word as an identifier in Python, that raises SyntaxError. But it does let you shadow builtin names, because that is sometimes useful (though that's pretty rare).
 
Ohh yes, I see, you only get in trouble with list or any other non reserved keyword if you use it for it's actual purpose somewhere in the code
 
@Kevin
% python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> await = 5
 
Results may vary ;-)
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> await = 5
  File "<stdin>", line 1
    await = 5
          ^
SyntaxError: invalid syntax
 
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:39:00)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> await = 5
File "<stdin>", line 1
await = 5
^
SyntaxError: invalid syntax
 
4:10 PM
Works fine in Python 2.7 :p /me ducks and runs...
 
@JonClements hahaha. No, you weren't in the crosshairs. Like I said, I have nothing against the library. This particular person really forces a 1-liner and itertools gives them scope to make some seriously incomprehensible code. Or to me, at least
 
From this experiment we've empirically concluded that a name that is reserved in one version of Python can still be used in another version where it isn't reserved. In other words, they don't bother to backport keywords.
 
BTW just out of curiosity, is there a surefire way to avoid problems like list = [1, 2, 3]
 
Think most linter's warn you about it...
 
4:14 PM
Remove the L key from your keyboard.
 
No, apart from having people read your code & telling you not to do that. ;) Or using an IDE or linter that tells you it's a bad idea.
 
yes pylint does tell me that, ` W0622: Redefining built-in 'list' (redefined-builtin) `
 
@Kevin Backporting keywords that don't work in that version gives no benefit, but may break existing code.
 
but does linters stop short of using a function name of a imported module as a variable
 
Good thing they don't do that, then.
Puzzle: what is the smallest number of keys you need to remove from your keyboard before you can't type any of the names bool, bytes, dict, float, int, list, object, set, str, tuple?
 
4:17 PM
e.g. this doesn't throw an issue in linter
from itertools import *
product = 3
ohh why is that a good thing @Kevin ? Why do you say that?
 
oh now you ask that... @Kevin... great... when a I can type is boo, bytes, dict, foat, int, ist, object, set, str and tupe now... !!! :p
 
I think a linter would need to solve the Halting Problem in order to prevent you from ever overwriting any function.
@DeveshKumarSingh To clarify, I mean "it's a good thing that they don't backport keywords, because that would unnecessarily break already-working code"
I wasn't talking about linters or anything
 
@DeveshKumarSingh The linter should give you a stern warning for using a star import. ;) Star imports aren't always evil, but they generally shouldn't be used like that, as we discussed here a few days ago.
 
so if I understand @Kevin linter would need to know about every function in every imported library , hence you say halting problem?
Yes it does say unused-wildcard-import @PM2Ring when i do wildcard import
 
Just knowing the name of every function in every module isn't enough. It would be literally impossible for the linter to stop you with perfect accuracy.
 
4:22 PM
That's interesting, could you care to expand on that @Kevin
 
@DeveshKumarSingh If you want to read the star import discussion, it starts around here
 
If the goal is to never let you reassign a name that's currently bound to a function, this is impossible to detect at parse-time. Consider the program x = random.choice([1, math.sin]); x = "blah". Sometimes this program binds a function to x and then overwrites it. Sometimes it doesn't. So a linter would not be able to tell you with certainty whether x = "blah" is a violation.
This is still a problem even if your program is completely deterministic.
 
ohh that is like predicting the future by the linter
or predicting program branches, or program behaviour
which is non deterministic
 
Deterministic example
import math

def extremely_hard_math_problem_that_takes_one_million_years():
    """this function either returns True or False. We don't know which one yet, because it takes a million years to run."""

def f():
    if extremely_hard_math_problem_that_takes_one_million_years():
        return 1
    else:
        return math.sin

x = f()
x = 99  #is this a violation? We won't know until a million years from now.
 
That's optimistic... it'll probably never reach x = 99... the Vorgons will probably have blown up the planet the computer's running that process on probably just 5 minutes before it completes and the mice will get really upset again... we know how that one goes... :p
 
4:28 PM
rip linter.
well, i suppose we all know the answer then. ;)
 
just waiting for the Question... taps fingers... :p
 
As for @JonClements question, he was right!
li = ['bytes', 'dict', 'float', 'int', 'list', 'object', 'set', 'str', 'tuple']

print(set.intersection(*[set(list(s)) for s in li]))
gives us t
the only character we need to remove from the keyboard to people to stop using reserved keywords which was mentioned
but bool spoils the party, since it doesn't have a t
 
Also several types that I left out such as complex and zip and super
 
yes, but this actually shows how easy it is to built complex things with list-comprehension! And yes you are right @Kevin
 
eh
the answer is zero
just switch the keyboard of the unsuspecting programmer to dvorak
 
4:34 PM
Then the person can't even code lol
 
@Kevin maybe go for... import keyword; kws = keyword.kwlist + list(vars(__builtins__)) or something ?
 
and if he can type with that...well he probably deserved to be able to overwrite builtins anyways, probably knows what he's doing. He's got the creds!
 
Wouldn't it be wild if there was a type that's still a type even if you unknowingly type it on a dvorak keyboard? Like maybe set becomes str or something.
 
that would be wicked hilarious in any case.
 
Never heard of keyword module before, this is amazing @JonClements Thanks!
wonder If I can find a dvorak to qwerty character map anywhere, and run it through all the reserved keywords, and see what @Kevin actually said holds true
that set becomes str etc
 
4:38 PM
Ummm... so maybe:
>>> set().union(*(el.lower() for el in keyword.kwlist + list(vars(__builtins__))))
{'r', 'h', 'b', 'k', 'p', 'a', 'y', '_', 'c', 's', 'l', 'f', 'q', 'n', 'o', 'x', 'u', 'j', 'd', 'm', 'i', 't', 'v', 'w', 'e', 'g', 'z'}
 
qwerty = "qwertyuiop[]\\asdfghjkl;'zxcvbnm,./"
dvorak = '"<>pyfgcrl?+|aoeuidhtns_:qjkxbmwvz'
d = dict(zip(qwerty, dvorak))

def convert(s):
    return "".join(d.get(c, "?") for c in s)
print(d)

types = ['__loader__', 'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'enumerate', 'filter', 'float', 'frozenset', 'int', 'list', 'map', 'memoryview', 'object', 'property', 'range', 'reversed', 'set', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'zip']

for t in types:
    print(t, convert(t), convert(t) in types)
 
probaby needs a slight reduction because zip is probably the only one with z and can be "covered" by removing p... but I can't be bothered to do that right now... leave that up to someone else :)
 
Answer: nope
 
Damn, @Kevin you are fast! So seems like we can be safe with a dvorak keyboard :)
 
@DeveshKumarSingh Terminology nitpick: these aren't reserved keywords. Only the names at docs.python.org/3.6/reference/lexical_analysis.html#keywords are reserved keywords.
 
4:41 PM
anyway... food time... bbiab
 
so just keywords will be a good term for them ?
 
@Kevin I'm not gonna lie, the speed with which you came up with that has impressed me greatly
 
I sure hope I transcribed the dvorak layout from Wikipedia properly.
 
Yes, not even google came up with a mapping for a dvorak to qwerty mapping
Although if this was a question on SO, if would have been downvoted to oblivion, and closed as too broad :D
 
Good thing we have no standards in here :-P
 
4:45 PM
true that :)
 
Of course.. all the numbers and the alt/alt-gr keys would need to be removed as well to avoid cheating :p
 
anyways, I think I have learned more beautiful things about python on SO then the 2 years I have spend coding on it! So I am thankful for that!
btw @Kevin I had a question, why did you not do
for t in types:
print(t, convert(t), t == convert(t) in types)
in your code, but you did
for t in types:
print(t, convert(t), convert(t) in types)
and both gives us the same result
 
Thanks to operator chaining, t == convert(t) in types is equivalent to t == convert(t) and convert(t) in types. Which effectively only evaluates to True if the qwerty-to-dvorak conversion doesn't actually change the string at all.
 
t == convert(t) would never be true
 
aah the in operator works in convert(t) in types
 
4:51 PM
er, yeah he said it much better than me :P
 
essentially checking for membership
I thought this was a new way of using print I have never heard of :P
 
@DeveshKumarSingh No. Just call them builtin names.
 
understood @PM2Ring
 
@AnttiHaapala about time
 
4:56 PM
is this somewhere in europe @AnttiHaapala ?
 
@DeveshKumarSingh Sorry, my last message was probably a little harsh. You can call them keywords, but the problem is that many people treat "keyword" & "reserved word" as synonyms, so we get back to the original problem. ;)
 
@AnttiHaapala It's supposed to be late autumn here. We've had a few cool days, and a couple of chilly nights, but for the last week daytime temps have been in the low to mid 20s.
 
haha it wasn't harsh @PM2Ring but sure lets call them no no words ?
 
:)
@WayneWerner But those are reserved words. That's a different category to builtin names like list, dict, etc, which are on the same footing as names you define yourself.
1 hour ago, by PM 2Ring
@DeveshKumarSingh You can"t use a reserved word as an identifier in Python, that raises SyntaxError. But it does let you shadow builtin names, because that is sometimes useful (though that's pretty rare).
 
5:10 PM
I've been frustrated at the documentation's imprecise terminology before, although I forget what specifically it was
Here's an example. Half of the things in "built in functions" aren't functions.
 
Naming things is hard. Naming categories of names is even harder.
@Kevin True, but if the docs called them "built in callables" it would be less friendly to the newbies.
 
Yeah.
 
5:24 PM
I shadow id all the time in functions
I'd guess that I shadow id more times than I actually use id
because I don't think I ever care about the id so much as the identity which I check with is
 
I used to overwrite file a lot. I still do, but it's not a builtin any more. So I guess I won :>
 
@Kevin in python 3.6 152 __builtins__
 
@WayneWerner as one should
 
@Kevin 59 are not types
 
@AndrasDeak and now I'm envisioning an evil Python coder cackling in his basement while he writes if id(this) == id(that):
 
5:31 PM
I almost never use id(), although it sometimes can be handy when debugging. But I have used it in oddball __hash__ methods.
 
152, and 48 are functoins
 
If you're saying "the tiny little list of type names from your qwerty-to-dvorak program is hardly representative of all the types in __builtins__, of which there are ~94", yeah. A bunch of them are subclasses of Exception so I skipped them
Or perhaps you're saying "It's wrong to say that half of __builtins__ aren't functions, because actually about two thirds of them aren't functions".
You got me there.
I will be more specific. Of the 69 entries listed under Built-in Functions, 42 of them are of the class builtin_function_or_method, 26 are types, and 1 is a _sitebuiltins._Helper
Let's call it 61% functions.
 
Happy Friday afternoon all!
 
ItM
It's so annoying that Python 3's division adds a .0 if it's an integer division like 4/2 = 2.0 and not just 2. Using // is not always what's needed as 4/10 should be 0.4. Any way to get rid of those trailing zeros?
 
5:47 PM
Just stick to Python 2
 
@ItM Well, Guido originally agreed with you, but it turned out that it wasn't such a good idea after all.
 
so you want it to sometimes be int and sometimes be float?
 
Actually yes, that's what their question seems to say stackoverflow.com/q/55974435/2301450
 
Perhaps the best solution is not "discover a form of division that dynamically returns an integer or a float, whichever is appropriate" but rather "find a method of formatting floats for display so that it cuts off the decimal point if it's a whole number"
In cases like these it's often useful to separate your requirements into logic vs presentation. Is it really so bad if the value is stored as a float, as long as it gets printed to look like an int?
(not a rhetorical question, the answer may vary depending on your needs)
 
def my_div(a, b):
    c = a / b
    if hasattr(c, 'is_integer') and c.is_integer():
        return int(c)
    else:
        return c

print(my_div(4, 2))
print(my_div(4, 10))

# 2
# 0.4
 
ItM
5:58 PM
I mean why add the .0? 4/2 is 2 not 2.0. At that point why not say 2.000000... It's just pretty annoying imo. But yeah, the trick comes to trying to display them correctly
 
wim
【PYCON】 any others from room 6 here (Cleveland)?
haven't seen any yet ...
 
/sigh... I wanted to be there this year
 

« first day (3121 days earlier)      last day (1828 days later) »