« first day (4244 days earlier)      last day (696 days later) » 

12:04 AM
stackoverflow.com/questions/1373164 I kinda hate that this has become our canonical, because of how OP is written. Could it be significantly edited without making the answers look like nonsense? How might we rewrite it?
 
What is a variable variable?
I didn't know this
 
there is a link there to a wikipedia article, but in short: OP wants the name of a variable to be determined dynamically (at runtime) based on the contents of a string.
i.e., the effect that you get by directly modifying the globals() dictionary in Python.
this is essentially never Actually What You Want To Do
 
Hmmm
So in Python using dictionary it works as intended?
 
12:38 AM
yes, although I have found that in most cases, OP really wants to label the values "serially", and thus should use a list instead.
 
Wow
I think I got it now
 
 
5 hours later…
5:42 AM
hi all, I'm having difficulty trying to update a value in a text file. I've been trying to find a fix for some time now and still couldn't find any help regarding this problem. So basically, what the code is doing is that it tests for the category name and the given category through user selection, if it matches, it will update the `total_events` column in the category file. But the thing is that I can't seem to get it update on one category because it increments all categories by 1.

Link to code: https://dpaste.com/FWH62CX7T
 
6:13 AM
Seems like it's a complicated case for me :\
 
@CoreVisional do you know what this does? filedata.replace(current_value, str(new_value))
 
@AndrasDeak--СлаваУкраїні yes, it replaces the whole file, that's another issue I couldn't resolve
 
I thought that was exactly your problem
 
yeah...currently I'm trying to instead of using replace, I'll assign the value based on index and write it to the file...
 
If you have a list instead of a string that will work
The most straightforward approach would be to loop over the file once and create a new file line by line as you go
So having an input and an output file open simultaneously
 
6:21 AM
@AndrasDeak--СлаваУкраїні alright, I'll try using the list first
hmm, are these suggestion together or the list part is separate. Sorry my brain is kinda foggy atm with all slicing and stuff..
 
If you have a list with every row in your input file you can replace only the rows you need and then recreate the file with changed lines. Exclusive or create a new file line by line.
 
ahh this one seems to work, it updated the first record, which is the category selected by the user. But now I'm not sure how to exactly update it in my file..

def update_category_total_events(category: str):
    filename = "event_management_system/data/category1.txt"
    records = split_category_delimiters(filename)
    for data in records:
        category_name = "".join(data[1]).strip()
        formatted_data = [item.strip() for item in data]
        if category == category_name:
            with open(filename, "r+") as infile:
 
Hi All
I could load the csv file in elastic using python, however i am unable to replace "," from a number field in csv before loading in csv...below worked for the 1st part
import csv
from elasticsearch import helpers, Elasticsearch
# Create the elasticsearch client.
es = Elasticsearch(['http://000000'], basic_auth =('xxxxx', 'yyyyy'))

# Open csv file and bulk upload
with open('test.csv') as f:
reader = csv.DictReader(f)
helpers.bulk(es, reader, index='test1')
can you please tell how to edit some column values.. e.g.. from column name "del" replace , with nothing from all the value( like 273,789 should be 273789)
 
@AndrasDeak--СлаваУкраїні does this mean I'll have multiple open() within the for loop?
 
if that works, yes... want to update csv before loading
sorry if that isnot relevant to my question
 
6:55 AM
ahh i can't seem to find how to properly write it to that one line. I tried opening both files at the same time and somehow it deletes the entire content..
 
7:25 AM
@CoreVisional did you by any chance use the same filename for both files?
 
@AndrasDeak--СлаваУкраїні oh, does the filename has to be different?
but to answer your question, yes i did
Anyways, I'm literally stuck on this. The progress I'm seeing is that I've changed the value in the list, but writing to the file just overwrites the entire content
 
Alas, opening a file in write mode will erase its contents.
 
7:42 AM
    well, now it just appends to the file with the old contents

    def update_category_total_events(category: str):
        filename = "event_management_system/data/category1.txt"
        records = split_category_delimiters(filename)
        for data in records:
            category_name = "".join(data[1]).strip()
            formatted_data = [item.strip() for item in data]
            if category == category_name:
                current_value = int(formatted_data[-1])
                new_value = current_value + 1
 
You might want to go back to the drawing board and write down what you want your code to do. This should be something like "read each line, for matching categories adjust a value, and write each line". If you want to understand where your code is going wrong, try to match each part of it against your description.
 
 
3 hours later…
11:02 AM
stackoverflow.com/questions/3012488 Is there a better duplicate/reference for "why should I use a with block to open a file rather than closing it manually"?
I'm going to sleep; if you find/know of one, please use it here: stackoverflow.com/a/72433175/523612
 
11:16 AM
Is it also for you surprising that two lines of a = std::chrono::high_resolution_clock::now(); b = std::chrono::high_resolution_clock::now(); both give the same time to the ns? I would expect there to be atleast a ns difference, but it looks like the calls finish in under a ns, is that possible?
Computers are mindbogglingly fast
 
(that doesn't look like Python code)
 
;)
 
My system clock has ms resolution, afaik. Definitely less than ns.
Though high_resolution_clock should be pretty good..
 
11:30 AM
@Hakaishin half-serious remark: compile with -O0
 
11:52 AM
Speaking of C++: I need to duplicate a single module for different variants (think Thread vs. Process vs. ...) and was thinking "templates" but cannot find a way to do it nicely in Python.
If I do it as instances of a template "module" class, then nested classes don't bind to the instance. If I do it with a "module" factory function, then nested classes don't pickle (and I need to update namespace). If I do it as subclasses of individual classes, that's a lot of boilerplate for each variant. Any good alternatives?
I was pondering whether it's possible to copy a module and swap some of its globals, but that seems kinda nasty...
 
12:06 PM
@MisterMiyagi can you somehow use a template "module" class, but without nesting classes? What exactly do you mean by the instance binding thing?
 
12:25 PM
@Arne thanks Arne, this does look similar to what I had in mind
I have a small design question, in my utilities.py I have get_users which would give me a list of users, if I apply a decorator @extra the same function would give a list of users but with extra data, how should I go about implementing this?
I want any module using my get_users to be able to freely choose if they want the decorated version or not
 
12:46 PM
@Jake in that case don't decorate with @extra, just define a separate function. Or if you already have the decorator for other reasons, you could do get_user_plus_stuff = extra(get_users) instead.
 
got it, I actually have one more case where I am facing this exact issue, I have a ratelimit decorator, so I guess I have to do something similar to what you said and have foo_rate_limited
 
Alternatively, add rate_limit=None to the signature (default being "no rate limit") and choose an explicit rate limit when you need one.
 
that seems like a saner alternative
 
@KarlKnechtel here I believe "I am using" was also correct. "I use" sounds more like "every time I have to solve this problem this is what I use" whereas "I am using" sounds more like "this is the code I have right now that I'm trying to use". But I'm not a native so our mileage may vary.
 
1:36 PM
@AndrasDeak--СлаваУкраїні I need "nested" classes because many of the things I want to build are classes. By "failing to bind" I mean that a nested function is bound to the instance (as a method) but a nested class doesn't get access to its containing instance.
 
Is there a "class bound to its module" analogy?
 
__globals__ are the closest I can think of.
So, practically I have a lot of classes like this:
class FutureResult(Generic[R]):
    def __init__(self):
        self._ready = Event()  # <<< this should be different for thread, process, ...
        self._result: Union[None, Tuple[R, None], Tuple[None, BaseException]] = None

    ...
Which just rely on some rather generic Event (and Lock) type.
There's really no structural difference at all between the variants other than using differently implemented primitives.
 
1:59 PM
wow, I just read the ctx hack. Infect 10M users with 5$. That's what I call a ROI!
 
2:29 PM
Hello. Considering a Pandas dataframe, how can I filter rows by datetime index so I can get specific time from a datetime range? Example: get only the rows that has 09:00 time between 2022-01-01 and 2022-03-01.
 
 
1 hour later…
3:55 PM
@AndrasDeak--СлаваУкраїні this one is really nuanced, and beyond my ability to explain properly. "I am using" is good enough in context that I wouldn't call it wrong, but the simple present sounds better to me here (I am a native speaker). It's not really marking habitual aspect (like what you describe, although it can also have that effect).
oddly enough, "I am trying to use" would definitely be better than "I try to use"
in context it does sound somewhat like OP has a few distinct places in the project where the class gets used, but my judgement is based more on the idea that it's a statement about the code itself, rather than a statement about the process of writing the code
consider also "my project uses" vs "my project is using"
 
@KarlKnechtel that would sound different to me, for what it's worth
Anyway, you are the native
 
4:43 PM
en.wikipedia.org/wiki/Present_continuous talks about the difference between present continuous tense ("I am using") and simple present tense ("I use"). TLDR: "I am using this class" may indicate the class will be used only once; "I use this class" may indicate the class will be used frequently or habitually or constantly
To give a real example, I would be comfortable saying "I use this Point class to do coordinate math", because I have used that class a hundred times in the past and I intend to use it a hundred more times in the future
The Song class in that post seems a bit less general-purpose unless the OP is really dedicated to music-related projects, so "I use" might raise some skeptical eyebrows
 
typical my rewrites just say "I have this code:" so :)
stackoverflow.com/questions/72437547 it's been a while since I saw someone actually say "...if someone could provide the code for me" explicitly
re the ctx hack: the projects I can find on GitHub still show as being modified 8 years ago, as if the malicious code never got added, and they seem to be quite small projects (not a lot of code or commits) that aren't that popular ("used by" less than 100 on GitHub). So the claim of 27k downloads seems a bit hard for me to believe
 
5:08 PM
You can see it from PyPI's own stats
It only needs to be on the dependency tree of one popular repo and it can get everywhere
 
5:33 PM
I see
(if something like this can be useful, I think I should count that as a vote towards prioritizing my autojson project :) )
(is there a way on GitHub that I can easily check whether other GitHub projects are using mine as a dependency?)
(I guess the general approach would be something like "search for projects that have a pyproject.toml or setup.py file matching some regex involving my pypi package name" but... ugh)
 
Check if wim's johnnydep works in that direction
 
There were two previous close votes on a question, one suggesting a duplicate. I agreed with the duplicate, and closed the question. Now the original auto-suggestion comment is gone. I really like the duplicate and want to give feedback to the person who suggested it. Any way I can check which of the other two voters to credit?
 
6:05 PM
@KarlKnechtel it might be there in the timeline
And I doubt it really matters
 
 
1 hour later…
7:08 PM
@KarlKnechtel thing is, to find it would probably require an extensive recursive search. A relies on B, relying on C that lists ctx as a dependency. It wouldn't surprise me if there was a way to get pip to build the tree for a package and show you, but otherwise it'd have to crawl PyPI potentially?
 
7:49 PM
>A relies on B, relying on C that lists ctx

in this case, I probably only care about C, and otherwise I could recurse manually.
I was envisioning a "flat" search/crawl of PyPI or GitHub etc., yeah. I'm not trying to check a specific project to see if it recursively uses a specific thing; this is a vanity "does anyone care about my FOSS releases to do something cool with them?" thing
maybe the "stars" on github are enough of an indication.
 
It would be vanity in your case, perhaps, but for the ctx issue, it would be good to be able to see what caused you to become one of the 27K "people" (or instances) affected. There is no easy way for me to know whether I've inadvertently brought it in on my shoes other than to pip freeze every project and check
 
 
2 hours later…
9:41 PM
N.B. case object(): also matches everything. — Raymond Hettinger Nov 8, 2021 at 14:42
just noticed that one...
 
very unastonishing
 
I didn't know that Python had a switch-like statement
 
10:00 PM
it's not very switch-like
 
Why?
 
you'd have to ask the core devs
the bottom line is probably because it's not "switch", it's "structural pattern matching"
 
Wow
I'll study it better on a day I have time
TY
 
Which, given that everything (?) Inherits from object isn't surprising. I might be brazen enough to suggest that the rust match works the same way
 
Everything inherits from object, yet val == object() is true for a very specific subset of values.
 
10:07 PM
I'd have to test whether it complains that some conditions are unreachable vs. Just being happy that it's exhaustive
 
The curious thing is that surely there must be a good reason why Python doesn't have a switch-like statement.
And I would like to know this reason.
I will order a switch via PEP.
 
Why?
 
I could build a mental model around case [foo]: and case object(): being analogous. But then we also have literal patterns which do use ==.
 
@Marco rejected!
 
@roganjosh I like the switch statement, huh.
@vaultah Why? :(
 
10:12 PM
Guido reasons. It was proposed and rejected in 2006. peps.python.org/pep-3103 Normally I'd say "you shouldn't try to suggest it again", but they accept pretty much anything into the language nowadays
 
:P
 
"I like it" isn't a very compelling argument. I'm not against new syntax, as it happens, but I also don't feel myself cuffed in python very often
 
I will fork CPython's repository and implement a switch to me
 
> Numbers and strings are compared using the == operator.
The singleton literals None, True and False are compared using the is operator.
^ that's reassuring to read, but also very magicky...
I wonder what happened to "If the implementation is hard to explain, it's a bad idea."
 
@roganjosh Do you see no use in the switch?
 
10:14 PM
No
That's not to say that I'm not missing something, but it is to say that I'm able to express what I need in the language as it is
 
@vaultah "Alternative 4 - [...] Unfortunately now we are forced to indent the case expressions, because otherwise (at least in the absence of an ‘else’ keyword) the parser would have a hard time distinguishing between an unindented case expression (which continues the switch statement) or an unrelated statement that starts like an expression (such as an assignment or a procedure call). The parser is not smart enough to backtrack once it sees the colon. This is my least favorite alternative."
Are you thinking what I'm thinking, Pinkie?
 
So it's "let's just use various if-elif-else" statements?
@vaultah Wow, I will read your edited message right now.
@vaultah Very interesting (the PEP), I will read it later... But I was just ironic, surely I knew it was discussed and rejected before, so it's impossible to try insert the switch in Python.
 
@Marco What's wrong with that? Or packing functions into a dict?
 
@roganjosh Well, I think that using a switch the code can be cleaner...
Packing functions into a dict is good.
 
I'm sorry to say that the amount of code I review that can't use the existing constructs makes me very pessimistic that adding yet more syntax is going to help anything
 
10:23 PM
Yeah, maybe no
 
10:38 PM
Neither add a variable variable is going to help anything.
IMO.
 
fwiw, I have in mind a proposal for range literals, which was tried a long time ago. Because `range` works differently now, it makes sense now. (Also, the original proposal was broader, allowing for ranges to be interpolated in list displays. This obviously doesn't make sense with the new `range` type, so it wouldn't be in the new proposal.)

actually I thought of that a few years ago. :/
anyway, we have two tools now: match-case, and (the traditional) dictionary-lookup-based dispatch.
 
Dictionary-lookup-based dispatch seems nicer
 

« first day (4244 days earlier)      last day (696 days later) »