« first day (2825 days earlier)      last day (2122 days later) » 
02:00 - 21:0021:00 - 00:00

2:59 AM
CBG
 
3:13 AM
argh, of course someone told that guy to edit locals(). At least the horrible metaclass option isn't available on Python 2.
 
3:46 AM
Y'know what like for my home workstation setup?
A two-machine setup with some networked drives and like, peripheral (particularly kb+m) sharing, etc. In a style such that switching between the two is setup like switching between monitors or workspaces, rather than having to focus a VM window. Mainly so that I can Windows when I sometimes (e.g. when gaming or being forced to used windows-only development like Unreal) to without needing to reboot, etc and still leverage my customised linux setup etc.
Just like uh
Windows as a workspace in my linux system I guess?
I'm expecting that VMs wouldn't really cut very easily since most of my need to use Windows also demands GPU access for the OS.
Although wait. I'm guessing it isn't, but it is possible to have two GPUs of radically different power installed, and hotswap their allocation to the core OS and to VMs, rather than having them throttled by the power of the lower unit?
Plus I guess, the guest Windows would probably underutilise the GPU although that might not be the worst-case-scenario.
Although wait
Could I set up device-over-network tech like Synergy to smooth over VM in-out-switching or something?
Oh wait. This is super off-topic. Sorry xD
 
4:22 AM
ha :D
 
4:49 AM
0/
 
cbg
 
5:11 AM
wb
 
5:47 AM
cbggggggggggg
 
6:00 AM
0/
 
Morning cbg
 
 
1 hour later…
7:12 AM
cbg
 
8:06 AM
Cabbage.
 
I've been reading the email thread about verbatim names on python-ideas, and I'm starting to wonder what some of those people are sniffing code.activestate.com/lists/python-ideas/50264
 
What would be the point of it? Underscores seem fine
I should think that would also cause confusion. \n*ame* or name?
 
8:36 AM
Good morning :)
 
9:06 AM
cbg
 
9:43 AM
hello o/
slightly niche tooling-related question: I discovered yesterday (after losing some time to debugging) that 'foo' 'bar' is identical to 'foobar', because I had missed a comma out in a subprocess arg set and couldn't work out why it was executing gitrev-parse instead of git rev-parse. Does anyone know if there is an inspection in pycharm to warn about those C-style string literal concats, and prefer explicit +? It would have saved me a not-insignificant amount of time
 
9:57 AM
@DaveRandom Not sure, but since it's completely valid syntax, I suspect the probability of such a tool / option existing to be quite low.
 
:-/
tnx anyway
 
@DaveRandom But you may always try a regex search!
"\s+" or something on those lines, depending on the data
 
well sure, it's more that I'd like something to warn "live" about the probable bug I just introduced with (what I might call) "implicit concatenation"
 
hah, I got nothing for that
 
maybe I will make one, fiddling with IDEA plugins has been on my todo list since forever
I just have a feeling it will require hand-writing several MBs of XML because Java, though
 
10:03 AM
I use the atom editor, so I would likely write in Python :D
 
According to this there should be a way to make custom inspections without having to write a plugin, but none of those dialogs and buttons referenced in the instructions actually exist in my PyCharm
 
10:14 AM
sounds about right
I know in PHP Storm there are a load of things like that where the docs don't match the GUI any more, they moved a load of stuff around when they switched from semver-ish to the year.minor.patch versioning system, I wasn't using pycharm then but I'm guessing they did the same there since it seems to be laid out like php storm
 
10:43 AM
i'm learning and using flask framework at work. is it possible to use a flask app as PWA? otherwise, what's the best way to give offline access to a flask app?
 
@manas
happy learning, yes you can create PWA apps using flask
 
@min2bro thanks. anything specific you can point me to? googling PWA + python + flask doesn't seem to show way.
 
jpp
Potential duplicate: stackoverflow.com/questions/51282642/…. Please review carefully (I closed, but another gold badger re-opened).
[Of course, it's contentious what's the best duplicate target.]
But think it best for community to decide as per this meta.
 
11:00 AM
@DaveRandom one intentional use case for that is multiline long strings inside parentheses
 
11:52 AM
Woo hoo.... got heapq into an answer...
Strangely always feel happy when I get ast or heapq into an answer...
 
I usually feel bad about using ast, because the 2nd sentence in the documentation is "The abstract syntax itself might change with each Python release"
 
12:20 PM
I have a feeling that this guy doesn't even understand his C++ code
 
@Aran-Fey yeah... they're getting a little confused over a few different things there...
 
12:44 PM
Cabbage
@DaveRandom I agree that literal string concatenation can cause mysterious bugs when you do it unintentionally, but some of us do use that feature intentionally. :) FWIW, it even works with f-strings.
 
@AndrasDeak could I still use + here?
 
Is there a PyCharm plugin that slaps you if you write code in the master branch? I need to get over this bad habit
 
@JonClements I haven't used heapq in many answers, but I did mention it yesterday in a comment:
Generally, the 2nd way will be more efficient, unless you rarely append but read a lot. However, Timsort, (which is O(n log n)) is very good at handling data containing sorted subsequences, so your 1st option may be ok if appends aren't too frequent. But also consider a data structure that can maintain sorted order, like some kind of tree, even the standard library's heapq may be useful, depending on your actual use case. — PM 2Ring 23 hours ago
 
@Aran-Fey A lot of hosted git services (github, gitlab, bitbucket etc) have options to make master read-only unless you are doing a merge, I saved a gist with a pre-receive hook to do it once, I will see if I can find it
 
@DaveRandom Sure, you can use + there, but literal concatenation is superior because it happens at compile time, not run time.
 
12:50 PM
@PM2Ring oh that's the difference, makes sense, tnx
although tbf that feels like epic micro-optimisation, and also like a possible easy-win compile time optimisation if all + operands are literals
 
Of course, the difference in runtime is miniscule, but IMHO when you want one string it's nice to tell Python to create one string rather than three (two temporaries and one final).
 
@PM2Ring absolutely, does python do immutable interned strings for that sort of thing?
 
@DaveRandom Good point. It might even be compile time optimized. Let's check...
Yep. It looks like it is. :)
>>> dis("a = '1' + '2'")
  1           0 LOAD_CONST               3 ('12')
              2 STORE_NAME               0 (a)
              4 LOAD_CONST               2 (None)
              6 RETURN_VALUE
 
I'm just glad people don't abuse string literal concatenation to write unreadable code like they do in bash: echo 'That'"'"'s how you escape apostrophes in bash'
 
cool, well I may make a plugin for the inspection, because it feels like one of those "you can but you shouldn't" things (to me)
 
12:57 PM
@PM2Ring Was using it here to pick a random line from a potentially large file...
Actually, I suppose it's just one, can use min/max - I'll update
 
@DaveRandom you rarely have to
 
@JonClements And I guess I also should've mentioned the bisect module in that comment. I keep forgetting it exists. :)
 
@PM2Ring :)
 
\o cbg
 
1:38 PM
@user2357112 "str.join [...] has to keep allocating bigger backing buffers for the list" Good point, but remember that list_resize overallocates to give linear-time amortized behavior, whereas string concatenation in a loop is O(n²).
OTOH, str has been optimized to give improved performance for smallish common concatenations, because some core devs realised that you just can't stop people concating strings in a loop. Other devs, like Alex Martelli, were not pleased with this development.
 
DSM
2:26 PM
greeting = ''
for c in ['c','a','b','b','a','g','e']:
    greeting += c
print(greeting)
 
Petition the devs to make string concatenation in a loop O(N!), to toughen up the youngsters that don't know better
 
What is this cabbage thing? I only know that cabbage is healthy... :D
 
@DSM wow... You'd think by now you'd be aware of str.join :p
 
>>> import dis;dis.dis("a = 'c' + 'a' + 'b' + 'b' + 'a' + 'g' + 'e'")
1 0 LOAD_CONST 11 ('cabbage')
2 STORE_NAME 0 (a)
4 LOAD_CONST 5 (None)
6 RETURN_VALUE
concat its pretty fast in Python, I can say... ;)
 
wim
2:39 PM
*CPython
@Aran-Fey what do you mean by "write"? edit a file? commit a change? push a change?
 
edit a file
 
wim
So you mean like the way it warns you when editing a file that's outside of the project?
 
pretty much, yeah
 
wim
hmm.
May I offer you an alternate opinion. There is nothing wrong with editing in master, and even committing to master is fine.
It is pushing to origin/master that needs to be protected.
This is distributed VCS. your local master is no more special than any other local branch.
you can accidentally make 100 commits to your local master, and then just create a new branch before making the PR - the remote will have no idea that your commits went to master and weren't in the feature branch the whole time.
makes sense?
 
2:57 PM
You've got a point there
 
cbg
 
aye aye cap'n
 
Hello Guys, need your assistance. I am fairly new to python and i need a help with string find(). i have a text AABBB-CCCDDD001 and i need to extract only CCC that is, after '-'. I am trying this: name = {} user = name[name.find("-")+1:3] print(user) the script runs but i am getting blank output. what could be the problem? please help
 
@KaranM Hello. Is your string always going to have that exact structure?
 
not necessary. but 90% of the text that i have is in this format. and for the exceptions i think i should be able to create if condition
 
3:01 PM
cbg all
 
@KaranM That code is a bit weird. name is a dict, and dicts don't have a .find method
 
@PM2Ring I am sorry, it's not a dict here. I am reading it from a csv file and storing it in a variable name
 
s = 'AABBB-CCCDDD001; s.partition('-')[2][:3]` (or rpartition maybe)?
 
If your string will always have the '-', I would first split on the....
kevin'd
lol
 
@idjaw grrr... where you hidden the nice biscuits... grumble grumble :p
 
3:03 PM
why partition and not split?
 
@MoxieBall partition is much for efficient for a single split... even more so than split with a maxsplit argument of 1
 
Neat, thanks
 
@JonClements This one worked Jon!
 
Slight difference is that partition will always return a 3-tuple so even if the - didn't exist, you'd get an empty string, rather than trying to index element 1 in a list and get an IndexError... but generally the former is desirable
 
@KaranM In that case you shouldn't have name = {} :) But anyway, here's a repaired version of your code:
name = "AABBB-CCCDDD001"
idx = name.find("-")
if idx >-1:
    user = name[idx+1:idx+4]
    print(user)
else:
    print("Not found")
#output
CCC
 
3:06 PM
@PM2Ring I will add a different format and try this one. Thanks guys
 
@wim Problem is, my use of git is very very sporadic. God knows when my last commit to side project #17 happened. I mostly make small changes and don't bother/remember to commit and/or push :/
I don't suppose there's a plugin that helps with that? :D
 
wim
that's your workflow problem
if you contribute to open source, or you work in a professional software environment where the repository you're contributing to is also being constantly committed to by other colleagues, then you will be forced into better workflow habits. and will naturally adopt those habits for your side projects too.
 
@KaranM So the reason you saw no output is that name[name.find("-")+1:3] slices from where the dash is up to the 3rd position in name, but that will be an empty slice if the dash is at or after the 3rd position. You actually want the slice to go to the 3rd position after the dash. But you should never just blindly use the index returned by .find unless you can guarantee that the thing you're looking for will always be found. Otherwise, you get this sort of thing:
name = "AABBBxCCCDDD001"
idx = name.find("-")
user = name[idx+1:idx+4]
print(user)
#output
AAB
 
Yeah, I really need to get into the habit to use git for literally every project (no matter how minor) and literally all the time
 
@PM2Ring This explained so well. Thanks for clearing my doubts. :)
 
3:12 PM
@KaranM I have a hunch that I should point out the section of the rules that says "Don't star posts to reward users for answering your question." nbd, I just like having the sidebar filled with funny things rather than answers to questions I won't care about in a day
 
@MoxieBall I am sorry. Will keep this in mind
 
Not a problem. Only star code if it's truly awesome. And / or funny. :)
 
Gratitude is never misplaced :) stars are
 
DSM
"The Lost Star" sounds like the name of a made-for-TV SF movie from the 1970s.
 
wim
3:16 PM
anyone else thinks this "dupe" closure is kind of gratuitous?
 
@MoxieBall There's a Hendrix song that mentions misplaced stars...
 
wim
@Aran-Fey not sure if sarcasm or not :)
 
@wim yeah, not much obvious similarity between those questions except that they're about iterators
 
@wim No, I seriously need to do that. It's happened quite a few times that I've had broken projects lying around for months because of a "minor change" I made and didn't have the motivation to fix
 
3:32 PM
dual wield
 
Yeah that's what this person thought too glaceon.social/@BearishMushroom/100356567177541237
 
DSM
Definitely with the tail. Having to put my head within striking distance of my foe to attack seems ill-advised.
 
But... isn't that what snakes do when they attack anyway
 
DSM
There's a reason I've eaten snake and no snake has eaten me.
 
You're too big?
 
3:34 PM
Plus all of those muscles for striking would be good for making a knife go fast
And having to hold a knife with the tail would impact mobility
 
DSM
I can't think of a practical way to test this, unfortunately. (I guess we could take to snake experts, who might say "tail couldn't do this" or whatever, but that's the boring approach.)
 
I still chuckle when reminded that the name for one who studies reptiles is a herpetologist
 
wim
herp derp
should I reply "buy a real computer" here or would that run afoul of the be welcoming wagon
 
We are lucky that lemurs didn't discover knives before humans
@wim I think "Install linux" is an appropriate workaround for windows users
 
rb folks
 
3:54 PM
I have a DAQ that I connect to via ethernet and I'm building a CLI to download the log files rather than using the included web interface. I can get the downloads fine, but the only thing I can't figure out is how to erase the log files. In the web interface there's an "Erase All" button that pops up a confirmation dialog, but it seems like I'm matching the POST, getting a 200, but nothing is being erased: gist.github.com/sco1/810fac0a93a8e5bffdd743966f36132a
what am I missing?
 
some of those are pretty lame. But I could identify with #7 and #9
 
4:42 PM
#8 would drive me crazy
 
@wim I went to add a a better dupe target, but then I noticed that the OP had already linked it in the question body. I did find another potential target, but it's not as good as the one the OP already had, so I just left it in a comment.
But it's a worry that he'd already studied the answers at stackoverflow.com/questions/19151/build-a-basic-python-iterator and couldn't figure out how to make his own iterator work. Sure, it can be a bit bewildering trying to do this stuff when you're new to it, but still...
 
@MoxieBall Yes but that question is asking to resolve what the tag should mean and how it should be used, not just asking for a simple up-or-down vote on a Python-centric counter (which I agree would not be very useful). So the fact that the tag is currently not being applied much is irrelevant. Please do post your own answer on the question and set out your thinking.
 
@PM2Ring why not add them anyway?
 
4:58 PM
@AndrasDeak Ok. I'll add the 2nd one I found, but it seems weird to hammer a question with a target that the OP themself has already linked.
 
I guess. Not unreasonable in general, but I didn't read this exact instance
 
I figure that if they already know about the target, hammering their question with that same target isn't very helpful to them. The message says "If those answers do not fully address your question, please ask a new question." And the OP is already asking a new question.
 
Anyone know the correct usage of os.PathLike? Like, if I have a path-like object, how do I actually use it? Am I supposed to call __fspath__() on it or what?
Oh, I guess I call os.fspath.
 
wim
it's just there to easy the transition from os.path badness to pathlib goodness
 
@smci I earlier suggested that re-tagging Python questions with seems reasonable, but the more I think about it, the less I like : it's a motley collection of collections, that don't have a lot in common, apart from the fact that they're collections, ok half of them are dict-based.
What actual benefit is there in tagging a question with it? Are there python-collections experts watching the tag, waiting for questions that need their awesome collections-handling skills? I don't think so. :)
 
wim
5:09 PM
@smci why do you care so much about it
 
@JonClements sorry pup. Didn't do the groceries. Top right shelf. All yours.
 
@idjaw aww thanks... I'm feeling tired... so you keep 'em... (or move them much lower down :p)
 
I'll have a bowl set up on the deck. Get those snacks and get some sleep
 
aye aye cap'n! - you're the best... falls asleep
 
@smci I currently don't have the energy to devote to a well-thought-out answer to that post, but my python-centric comments on it really stem from a non-python-centric sentiment that the tag is useless because it is a relatively specific thing that requires very little expertise to answer a question about in all but the CSS and SQL cases where the word "counter" has a special meaning to someone using those languages. I have a very similar sentiment towards the tag.
If a tag is going to exist for the most basic control flow patterns, might as well just make not specific to python and call it a day, and let people add useless tags to their questions
 
5:25 PM
Which one of these is better?
if isinstance(obj, tuple(acceptable_types)): pass

if any(isinstance(obj, type_) for type in acceptable_types): pass
 
imo the first
cbg
 
@Aran-Fey Definitely the 1st, since it checks the tuple of types in a C loop, not a Python loop.
 
first one it is
 
BTW, your 2nd option has a type_ / type typo. :)
 
isinstance works with a tuple like that?
really?
 
DSM
5:39 PM
Score one for the 'use of intermediate variables in listcomps and genexps isn't as clean as map' side..
 
@idjaw Yep. Since Ancient times. Just checked: introduced in 2.2
 
In hopes of confusing idjaw even further:
>>> isinstance(False, (int, float))
True
 
DSM
Off the top of my head, isinstance, isssubclass, startswith, and endswith all accept tuples of their args.
 
@Aran-Fey stop confusing me!!!!!!
:P
 
:D
 
5:41 PM
how have I never ran in to this. This is pretty neat....but wat is up with that last one Aran posted
lol
oh wait
I get it haha
 
Honestly, I'm surprised that booleans being a subclass of int doesn't cause problems more often
It lets you do all kinds of funky stuff without throwing an exception: user_input = os.fdopen(False).readline()
 
I can't get this to work: isinstance(obj, tuple(acceptable_types))
 
@idjaw seems like someone needs coffee which I haven't stolen for a change! :)
 
keep getting arg 2 must be of type or tuple of types.....
yeah...I think it's time to stop doing things and just do things that don't use my brain
oh god I don't think what I wrote even makes sense.
 
FWIW, here's the latest version of my killer primes generator. I don't think it's possible to do this any faster in plain Python. I guess some people might not like my ceiling division trick. Or my passing a dunder method to takewhile...
 
5:46 PM
walks out
 
from itertools import count, chain, compress, takewhile
def primes_gen(lo=2, blocksize=100000):
    if lo <= 2:
        yield 2
        lo = 3
    else:
        # Ensure that lo is odd
        lo |= 1
    # Ensure that blocksize is even
    blocksize += blocksize % 2
    size = blocksize // 2
    for hi in count(lo + blocksize, blocksize):
        sieve = bytearray([1]) * size
        for i in takewhile(int(hi ** 0.5).__ge__,
            chain([3], chain.from_iterable(zip(count(5, 6), count(7, 6))))):
 
@PM2Ring You could appease them by partialing operator.ge I guess?
 
@JonClements I hate partial. It's as slow as a wet week.
 
Thank you for that expression PM. I never heard it. And I'm using it.
 
Speaking of boolean abuse, here's an excerpt from something I wrote last night that I just know Wim would hate. :)
glyphs = ('X+', 'Oo')[len(a) == 1]
b = [glyphs[u in found] if u in a else '-' for u in nrange]
@idjaw It's a good old Aussie expression.
 
5:50 PM
@PM2Ring yeah... not a fan of it myself really but just thought I'd point it out... just wondering if you could make use of divmod there...
 
@PM2Ring I have an Aussie on my hockey team. He hasn't used that one yet. I'm going to surprise him with this one.
 
@JonClements divmod is another annoying thing. It makes code more readable, but it's slower than using the operators. Although the speed difference isn't so bad in recent versions.
 
wim
@DSM and except
 
@wim and str.__mod__ :D
 
wim
ah, yes. that weird one.
partial
Jan 18 at 15:20, by wim
kinda belongs in the trash with everything else in functools
 
5:58 PM
I hardly ever use anything from functools
ever
 
@PM2Ring Hi! Can you please explain me why the condition you used is idx>-1?
name = "AABBB-CCCDDD001"
idx = name.find("-")
if idx >-1:
user = name[idx+1:idx+4]
print(user)
else:
print("Not found")
#output
CCC
 
I use lru_cache a bit, but it's really annoying that you can't initialize the cache. And since I rarely use the LRU aspect I mostly just end up using my good old favourite memoizing cache, and save on the extra function call overhead of using a decorated function.
@KaranM Because str.find returns -1 if it can't find the string it's looking for.
 
So I am trying to extract 'BBB' with the same condition but only changing user = name[idx-1:idx-4] And yet i am getting that same blank output.
I think I got it.
Changed it to user = name[idx-3:idx-0]
@PM2Ring It is giving me the correct output that i need. But, can that be used as -0?
 
@Karan idx - 0 ? :p
 
@KaranM user = name[idx-3:idx]
 
6:07 PM
Yes Jon! this is exactly what i did. and I am getting the output.
for row in reader:
name = row['CI_Name']
idx = name.find("-")
if idx >-1:
user = name[idx-3:idx-0]
print(user)
else:
print("Not Found")
@PM2Ring This works!
 
@KaranM And here we should also check that idx >= 3, since negative indices access the string from the right hand side.
 
@PM2Ring So there will be one more if condition along with that correct?
 
for row in reader:
    _, found, suffix = row['CI_Name'].partition('-')
    if found:
        user = suffix[:3]
        print(user)
    else:
        print('not found')
or simpler
for row in reader:
    user = row['CI_Name'].partition('-')[2][:3]
    if user:
        print('found:', user)
    else:
        print('not found!')
Or even more concise
for row in reader:
    user = row['CI_Name'].partition('-')[2][:3]
    print('found:' if user else 'not found!', user)
 
@KaranM .find is ok for simple stuff, when you're sure that the strings are always going to be in the right format. But I think Jon's way is simpler, especially since you want to extract 2 strings.
 
benefits of partition are that you're guaranteed an empty string on no delimiter present so slicing it returns empty and becomes your if index > -1 check by itself...
 
6:15 PM
Yes! The thing is, I am extracting not just 'CCC' but also 'DDD' and 'BBB'. I have created class-method for each type of string that i want to extract. and later on just as you mentioned, i need to remove the ones that are not following the format.
@JonClements Correct! But I suppose this won't be the go-to method to use if I want to check on the names that doesn't follow the format, right?
 
Well... until you elaborate who knows... you seem to be focusing on getting the first 3 characters after the hyphen... if only certain subsets of 3 characters are allowed - you could put those in a set and then do a membership test for user
 
This is the format that 90% of the names will be in: AABBB-CCCDDD001
And for the rest of them, I can use if condition just like @PM
@PM2Ring mentioned.
@JonClements I am not sure of that membership test Jon! I am still in very early stages of learning Python.
 
@KaranM If you know that the string will be correct if it contains a dash, then you can use .find, or partition. Eg,
def extract(s):
    idx = s.find("-")
    if idx > -1:
        return s[idx-3:idx], s[idx+1:idx+4], s[idx+4:idx+7]

for s in ("AABBB-CCCDDD001", 'bad'):
    print(s, extract(s))
#output
AABBB-CCCDDD001 ('BBB', 'CCC', 'DDD')
bad None
 
@PM2Ring Yes exactly you got my point! if it has a dash ('-') then it is following the correct format.
 
Otherwise, you need to perform more stringent tests on your input data to make sure that you aren't going to get garbage out of it. Depending on the form and reliability of the data, it may be easy to do that with standard str methods. Or you might need to use regex.
 
6:23 PM
Thanks guys! I need to perform joins in SQL as well first to get the right tables and everything but this was just the first part where I had to extract those correct codes in order to put them into SQL queries
@PM2Ring I looked into regex, but I feel i'll need a lot of time to get used to it. Although, that would be the best method when dealing with such type of data. But, currently i need to deadline, so have to get this up and running soon.
meet the*
 
Sometimes, you want to be really strict: if the data doesn't have the right format, just treat it as an error and refuse to process it. Eg, you don't want to contaminate your database with garbage data. t other times you want to be lenient, a Web browser will do its best to display malformed HTML, since it's usually better to display something, even if it has some broken parts.
 
Yes, I only need to treat them as error and make sure they don't get into the SQL queries.
But want the script to run all the names and leave the ones that are not following the format.
 
@KaranM Regex is a handy tool to learn. But it's not magic. And some people use it too much, and for tasks that it's not suited to. And it's very easy to write regular expressions that are very hard to read, which makes it hard to maintain code that does a lot of complicated regex stuff.
 
@PM2Ring Probably that is why I am scared of delving deeper in regex for now. Because, it is hard to read and don't want to make up any mistakes when I am doing a SQL query with these codes.
 
6:52 PM
I think if you comment on line with regex usage or string containing the pattern, it would help understanding the code
usually this works with all that non-obvious stuff, just a little comment
 
Honest question, is this readable?
extractor = re.compile(
  r'(?P<AA>\w{2})'
  r'(?P<BBB>\w{3})'
  r'-'
  r'(?P<CCC>\w{3})'
  r'(?P<DDD>\w{3})'
  r'\d+'
)
 
@Arne I think it's ok
 
I think it's ok too, although I don't normally use named groups, since I learned regex long before they existed. :)
 
I use them for everything that matches more than one thing by now
 
@PM2Ring I used them today as a horrible way of doing something in pandas :)
I think django was possibly responsible for a lot of people realising they even existed because of it's url(...) stuff
 
wim
7:18 PM
what's the dupe for don't mutate list while you're iterating over it
@Arne "readable" and "regex" is like oil and water
 
I see I got another honest answer
 
@JonClements yeah, I saw that (-:
 
every now and then I come across a problem where a regex is more readable than the code you'd have to write instead
it helps that every cs student is forced to learn them
 
Scissors are useful. Running with scissors is not smart.
 
@wim Sorry, our collection only has targets for removing list items while iterating, not mutating them. sopython.com/canon/95/…
POB stackoverflow.com/questions/51292902/… "Why there are almost no libraries and platforms built for machine learning and AI in PHP compared to Python ?"
 
7:36 PM
Opinon based? How so? Too broad maybe
 
Why would someone ever want to do machine learning in PHP?
 
They don't, that is why there are so few frameworks for it.
 
@Simon Because such questions will invariably devolve into a language war if they aren't nipped in the bud. And language wars revolve around "Language X is better than language Y", which is technically a matter of opinion... although it's pretty easy to argue that Python is objectively superior to PHP. :D
 
Well Python is better than PHP for most all things :p
 
@wim regex forms a firm support for a layer of readability?
 
7:44 PM
I think I see why it was closed, while it's a good question in theory, someone who loves PHP/Python will come along and argue against any existing answers.
 
o/
@PM2Ring pfffffff
>>> x = 'hello'
>>> b = 'hello'
>>> b is x
True
... does python like, internally create a hash of every string that is assigned to make that verification? What about arbitrary long strings?
 
it's about spaces
it's an implementation detail of cpython, and it's called string interning if you want to google
 
I sure do, thanks
 
there used to be a way to manually intern strings but I think they (re?)moved that in python 3
 
@FélixGagnon-Grenier Python doesn't intern all strings, it tries to be intelligent about it: it does it to strings that can be used as identifiers: variable names or attributes. And it doesn't always do it.
 
7:55 PM
I thought it always interns strings without spaces
 
@AndrasDeak You may be correct. :)
 
You use to be able to use intern in 2.x - it got removed in 3.x though
 
good, good
 
It can also intern strings with spaces. IIRC, the advice is: don't expect strings to be interned, just let CPython do it as it sees fit.
 
it's an implementation detail so one shouldn't rely on it anyway
 
8:00 PM
I was just now learning about immutable ints, garbage collection and object assignment, and wondered if it was the same with strings. such pandora box ;)
>>> x = 5
>>> b = 5
>>> x is b
True
From that, I think I understand that there is only ever one int(5) representation in a python environment, and that it's used everywhere
 
same thing with interned ints; those go from minus something to 255 or something
@FélixGagnon-Grenier yup
also things like the empty tuple is interned
 
@FélixGagnon-Grenier You may also find this info about Python's memory management interesting: docs.python.org/3/c-api/memory.html
 
>>> a = ()
>>> b = ()
>>> a is b
True
>>> a = (),
>>> b = (),
>>> a is b
False
 
the unary , is tuple declaration iirc?
 
8:04 PM
yup
that's short-hand for ((),): while () is the empty tuple (a) is not a tuple
 
@FélixGagnon-Grenier Correct. Small integers from -5 to 256 are actually compiled into the CPython interpreter itself.
 
but watch out because the interactive shell can be deceptive
>>> a = 1,; b = 1,; a is b
True
>>> a = 1,
>>> b = 1,
>>> a is b
False
(not sure whether this is actually about the interactive shell, just saying)
I suspect having stuff on separate lines shouldn't matter in a proper script
huh, in a proper script I get True for both :D
I guess it's smart when it compiles the script, but the REPL can only compile line by line
 
Also, the Python memory system is very good at recycling. Check this out:
a = []
print(id(a))
a = 999
print(id(a))
a = []
print(id(a))
# typical output
3071794924
3071742736
3071794924
 
@PM2Ring 😲
TIL
 
that can actually be pretty confusing when you try to look at that in a REPL
id can't really be trusted for identity, only for difference
 
8:12 PM
"hey python, can you give me a list?" "sure, I still have one lying around right here. good as new!"
 
aye!
I got a pytest thingie. Let's MCVE this and fail at it! :)
 
@Arne not the same list
>>> a = [1]
>>> print(id(a))
139662409431624
>>> a = 999
>>> print(id(a))
139662411990736
>>> a = []
>>> print(id(a))
139662409431624
or maybe it is, but not in the usual sense
 
@pytest.fixture
def some_fixture(mocker, another_fixture):
    another_fixture.foo = mocker.patch.object(TheClass)
    another_fixture.bar = mocker.patch.object(TheClass)
 
@idjaw xfail?
 
in this context mocker is the pytest-mock plugin.
Has anyone successfully used patch.object successfully without the pytest-mock plugin?
because the extra decorators on pytest.fixture does not work
@pytest.fixture
@mock.patch.object()
@mock.patch.object()
def fixture():
^^ does not work
 
8:15 PM
@AndrasDeak now I'm even more confused.
 
I suspect it reuses the head of whatever stores the list
Like reusing a longer string for a new shorter one
We could try the other way around
 
seems to me like objects that are up to be gc'ed may be recycled if they get the chance.
and for mutables they don't need to be equal to the new target either
 
8:30 PM
I am a stupid
my decorators were not ordered right
excuse me while I hit myself repeatedly
today is not a good day for my and my brain
 
Poor your :(
 
have you considered hitting yourself repeatedly may be a cause of you and your brain not having a good day? :p
 
wim
@AndrasDeak it's not about space
it's about identifiers
for example 'google.com' will not do the intern thing, because it has a dot in it, and that means it is not a valid variable name in python
 
@JonClements keanu woah meme
 
wim
oh, I see PM already mentioned that
 
8:35 PM
is my online repl drunk? repl.it/repls/TremendousQuixoticSearch
>>> a = 'google.com'
>>> b = 'google.com'
>>> print(a is b)
True
 
Welp Looks like my Boss is going to to buy my team dinner :( England lost
 
not surprised - we're rubbish when it comes to extra time :)
 
wim
@Arne weird
I can't check it because repl.it not working from firewall
 
@Arne: You're not using the REPL functionality there. Anyway, getting True or False from that comparison is an implementation detail.
The way you're running that code, it's all compiled in one block.
 
>>> a = 'google.com'
>>> b = 'google.com'
>>> a is b
False
thanks, wim
 
wim
8:41 PM
@idjaw why would you want to use the decorator version of patch
one of the best reasons for moving to pytest is so that you don't use those ugly decorator incantations of mock.patch.
 
import random
from string import ascii_letters

random.seed(42)
a = ''.join(random.choices(ascii_letters, k=10))
random.seed(42)
b = ''.join(random.choices(ascii_letters, k=10))

a == b, a is b
# (True, False)
 
@Arne Exactly. It saves time, and recycling as much as possible reduces memory fragmentation. Check out that link I gave FélixGagnon-Grenier about memory management. A lot of the stuff there is mostly relevant to people writing C extensions, but it's interesting to learn about memory arenas and related topics.
 
wanted to get the number 42 out there today :)
 
@wim So that actually brings me back to my original problem. I can't get it to work without using pytest-mock
 
Hey, 42 is my standard random seed. :)
 
8:46 PM
I now know what my minecraft seed will be forever
 
Hey, @MartijnPieters Someone at Facebook is making mojibake:
@PM2Ring This is what you get if you download a copy of your Facebook information in .json format. — daniel 4 mins ago
 
Unless, wim...pytest-mock is the solution here?
 
02:00 - 21:0021:00 - 00:00

« first day (2825 days earlier)      last day (2122 days later) »