« first day (4365 days earlier)      last day (583 days later) » 

7:13 AM
:55293539 Would the class have references to each of these classes then?

class Class:
    html_writer: HtmlWriter
    txt_writer: TextWriter
    db_writer: DatabaseWriter


obj = Class()
path = html_writer.location
Is this what you mean?
 
No, not sure why you have added the Class. Just use the Writers directly.
If you want several writers, have a list of them.
No need to restrict to just one of each kind.
 
Yeah, and here is where my problem arise... :')

class Report:
    writers: list[Writer]

    def __init__(self):
        writers.attach(HTMLWriter("path"))

The writers should be contained by this report class. The user should not need to interact with how the report writes to each of the outputs, but they will need to be able to know where each output is being generated.
Sorry for the confusion.
I don't want them to create the writers by themselves, that's what I mean.
report.open()

... opens up all outputs

report.log("hello")

... writes to all outputs

report.close()

... closes all outputs
They should only need to be aware of what to log, not how to log it.
They handled this by having all different output handling in the same class before, which is what I'm trying to avoid right now.
 
So you always have exactly one HtmlWriter, one TextWriter and one DatabaseWriter? You can't add a 2nd HtmlWriter, and you can't turn it off either?
 
7:29 AM
We actually only have a TextWriter and HTMLWriter right now, but by separating it now, I saw the possibility to easier attach a DatabaseWriter in the future.
But yeah, the class is required to have a HTMLWriter and a TextWriter.
 
Ok, then that design looks fine
But if the user only needs to know the path of the html/text file, then you should just expose that, and not the whole Html/TextWriter
 
That's true, I'll do that for sure. These classes will also probably be called _HTMLWriter and be internal to the specific module. :)
class Report:
     html_writer: HTMLWriter
     txt_writer: TextWriter

     def log(self):
         for writer in self._writers:
             pass
I'll miss out on the possiblility to do it like this now, but whatever
It's kind of good to have them as separate attrbitutes (if I want to log to a specific writer only), right?
 
Sure
 
Is this pattern suitable for Python btw?
tutorialsteacher.com/csharp/csharp-event
What I like with it is that you don't have dynamic events fired between objects, which the ordinary "Observer Pattern" tends to do.
 
8:00 AM
which is better or more generic or clean,

dictionary_object.get('some_key', str()) or dictionary_object.get('some_key', '')
 
''
 
dictionary_object.get('some_key', str(f"{str('')}")
 
@Warcaith brooo
@Aran-Fey thanks
 
@sahasrara62 <3
 
@Warcaith f''u''r''
 
8:07 AM
@Aran-Fey eyyy
 
8:43 AM
TypeScript is making me realize that type annotations are always a mess, not just in python. Soooo much unnecessary type casting to make VSCode shut up
 
yep, that's what I noticed too
I also feel like there way more TypeScript type annotations package vs Python ones
btw, how is your javascript project coming along Aran?
 
Well... I pretty much figured out how to reliably achieve the volume change, but now I'm toiling away creating a nice user interface
 
ah, that's nice :) so you managed to get around the CORS?
 
Yeah, iframes. You might end up downloading the same video twice, and decoding the same audio stream twice, but hey, at least it works
 
9:06 AM
Why can't I see my parents private "_attributes"?
I missed a decorator, that's why.
@dataclass :p
 
9:25 AM
@Aran-Fey maybe switch to jetbeans
 
I always thought jetbeans was for java though
 
I know Jetbrains and Netbeans, but not Jetbeans
 
sory jetbrains
 
> The [TypeScript] plugin is available only in IntelliJ IDEA Ultimate, where it is enabled by default.
I think I'll pass
 
9:52 AM
@Aran-Fey that explain why I thought of saying that
 
@Aran-Fey you can use ultimate for free, been using it for last 4 years
 
How do you use it for free? O.o
 
I think it's "always free" only if you use the student licenses (or if you have a popular open source project, etc)
 
 
2 hours later…
11:45 AM
Progress milestone for my pointless parsing thing: it understands lambdas pastebin.com/raw/G7L3EY8r
Not actually sure if that last test case is producing correct output. But any output is better than the one hundred stack traces that I had to wade through to get to this point
 
12:16 PM
@Warcaith Looks fine to me.
Above a certain level of abstraction, pretty much any design you can come up with will be "suitable for Python". If you're not doing pointer arithmetic or keeping track of a lot of array indices, that's a good sign.
For example, I reckon everything in Design Patterns: Elements of Reusable Object-Oriented Software is suitable. That's where I got the Composite pattern that I recommended to you yesterday.
 
12:58 PM
Thanks for the insight @Kevin. I've got a really good design now that I can work with, so thank you all! :)
I got a problem right now though. I have a pathlib.Path object that points to a file. I want to create the directories to the file before I create the file, but I end up getting a directory which is named after the file. Why is that?
 
You did path.mkdir() instead of path.parent.mkdir()?
 
Oh, yeah, the reason was that I wanted to support copy a file by new name, but also with the old name.
But it's easily fixable, just didn't think about that.
:p
Can't find any method in pathlib that checks if the path is formatted as a file or directory. The file and directory can be missing.
 
I don't know what that means. Paths aren't strings, what does it mean for a path to be "formatted"?
 
path = Path("D:\folder\file.png")
print(path.is_file()) -> False
print(path.is_dir()) -> True
Why does it behave like this?
(The file has not yet been copied to that destination)
Aaah...

Path.is_file()
Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file.

False is also returned if the path doesn’t exist
I can't use Path object to create destination paths that has not yet been created then.
 
morning cabbages, folks!
 
1:10 PM
@Warcaith Sure you can, why not?
 
source = Path("D:\file.png")
destination = Path("D:\folder\another_name_for_the_file.png")

print(destination.is_file()) -> False
print(destination.is_dir()) -> True

if destination.is_file():
    destination.parent.mkdir()

if destination.is_dir():
    destination.mkdir()

shutil.copy(source, destination)
 
Well, your problem is that D:\folder\another_name_for_the_file.png is a directory. You have to delete it before you can copy a file there
 
Why does it behave like this though? This generates a directory called exactly "\folder\another_name_for_the_file.png" with a file inside that is named "file.png"
Lol.
It feels like you are standing behind me and looking at my dumb problems.
Yes, it was exactly like that. I forgot to remove the weirdly named directories.
Embarrasing.
 
Actually, neither of those if statements make any sense. If a file already exists at the destination, you don't need to create the parent directory. And if the destination is a directory, you should delete it, not create it
 
Oh, I'm see that I'm not that great at describing my problem.
 
1:17 PM
Having little experience with Path, at first glance I was unclear on whether x.is_dir() means "the path string looks like it might be a directory" (i.e. it doesn't have a file extension) or "the path is a real path in the file system, and it points to a real directory"
... And similar for is_file. But thinking about it, I'm guessing that "it points to a real directory in the file system" is the intended meaning
The problem with the "looks like it might be a directory" interpretation is, there's no objective criteria for deciding whether a path could be a directory or a file. directory names can contain periods, and file names don't have to contain periods. "C:/foo.bar/README", for example.
 
This is what I really want to happen.

I have a **source** file that I want to copy to a specific destination. The destination can either be a **directory** or a **file**. If the user wants to move the source file to **folder1/folder2/folder3**, the source file (with the original name) should be moved into that folder, including having all parents directories generated. If the user wants to move the file to **folder1/folder2/folder3**, but this time with another name, I just want to generate all **destination.parent** directories and place the file inside the top level directory, with the n
 
> The destination can either be a directory or a file.
 
"The destination can either be a directory or a file" -- a valid goal, but might be tricky, exactly because of what I mentioned above
Oops beaten
 
Well, how do you tell the difference between the two?
Semi-Kevin'd
Kevin'd each other
 
That completely true, based on what Kevin said.
Hmm.. tricky!
 
1:23 PM
If you're only moving a single file or directory, perhaps you can keep track of what it is, using an is_file boolean or similar
 
Aaah, yes, it will only be a single file or directory. I can rely on that file completely, that's true.
 
Or you can deduce that information by looking at the source path, I suppose
Possible approach that I didn't test at all:
source = Path("D:\file.png")
destination = Path("D:\folder\another_name_for_the_file.png")

if source.is_file():
    destination.parent.mkdir()

if source.is_dir():
    destination.mkdir()

shutil.copy(source, destination)
 
Yeah, I wrote exactly that. I'll make some tests and see what I end up with.
Thaaaanks!
 
Can't say for sure without seeing the original indentation. Consult tinyurl.com/urnzp7k for formatting instructions.
 
Rnj
here is indented code : ctxt.io/2/AAAQ9vKsFQ
 
1:35 PM
In the meantime, I do have one observation that may be relevant. If you're writing code in a REPL or some kind of workbook, then you may have old global variables lying around from previous experiments. You might end up writing code that looks like it works, but really it's accessing old values that won't exist when you try to run the code in a more isolated environment
Ok, now that I see the indentation, it's probably not a REPL/workbook issue.
 
@Rnj You have two different palLen variables, one in longestPalindrome and one in checkPal. Add nonlocal palLen at the top of the checkPal function
 
Rnj
I am seeing the error in leetcode editor and also in my local jupyte notebook
 
I agree that nonlocal palLen is a good solution. The reason it is necessary in longestPalindrome and not in longestPalindrome2 is: you only need a nonlocal statement if you want to assign to the value. checkPal2 does not assign a value to palLen, so it can see palLen without using nonlocal.
 
Rnj
So palLen = curPalLen is re-declaring it in checkPal? Which is not the case in longestPalindrome2? Was just thinking why its working in longestPalindrome.
 
See also this question, someone (*cough*) wrote a good answer there
 
1:41 PM
Python doesn't have a native concept of "declaring", but something like that is happening, yes. Without the nonlocal statement, Python assumes that palLen = curPalLen wants to create a brand new local variable named palLen, which has nothing to do with the already existing variable palLen in the higher scope
 
Rnj
sad ... doing nonlocal adds one more line ... wanted to keep my code minimal for better intuition ...
I guess nonlocal behavior should be default and there should be local keyword?
 
For maximum intuition, avoid closure variables
 
Is SO new tab broken for search today?
 
Python says 'ok, so all occurrences of "palLen" inside "checkPal" must be referring to the new local palLen and not the older less-local palLen'. But then it sees that you're doing curPalLen > palLen on a line before the local palLen is first created. Python says 'I can't run this comparison! palLen doesn't have a value yet." and so it crashes.
 
Rnj
yeah I got that ...
 
1:46 PM
@Rnj But then, for every nonlocal statement you don't have to write, you'll have to write a hundred local statements. I prefer things the way they are now.
 
Rnj
I meant if there is nonlocal variable in immediate enclosing scope, just then consider it as it is highly likely that the developer wants it that way. For local variables not there in the immediate enclosing scope, they of course can omit local.
 
I think you could avoid nonlocal if you made checkPal return a value.
 
Rnj
yess that will certainly work
 
Hi, Is there a way to update a nested field in MongoDb using PyMongo. Link to sample document is here - stackoverflow.com/questions/73882492/…
 
$'set' isn't valid Python syntax, so I would expect that to crash right away. If you aren't seeing a stack trace, there may be a problem with your environment.
 
2:01 PM
Ugh, Ouroborous has been frozen
 
2:28 PM
if I have a class with an attribute foo which is a list and I iterate over it with a for loop. Sometimes I want to change the original list item and then I use for i, foo in enumerate(bar): print(foo) bar[i]+=1 this does feel kinda unpythonic, but how else would I go about modifying the element while looping over it?
 
Half joking proposal: create a class MutableInteger, with a method increment. Make your attribute a list of MutableIntegers. Then you can do for foo in my_list: foo.increment(), no special syntax required
 
(:
Maybe nothing is wrong with what I'm doing, I'm not sure
 
Sounds perfectly fine to me
 
Cool, you have always struck me the right balance between crazy kite and well grounded :D
 
I avoid assigning to a list while I'm iterating over it, but I don't have a strong justification for my preference
 
2:38 PM
it's list with dicts inside and I modify a field in the dict
 
Couldn't you do for the_dict in my_list: the_dict[field_name] = new_value then? That's fine by my standards
 
tbh I'm still not sure when to use a dict, a Dataclass or a Class. The usecases are such a fine grained spectrum that either one might work for all the other usecases
@Kevin dou, ofc
 
There's quite a bit of gray area when choosing between dict and class, I agree.
I like dict for prototyping, especially when I don't have a full idea of what structure my data will take. If I'm halfway through writing a function render_profile_page, and I decide I want the "author" element to have a "phone number" key, I don't need to alter any explicit schema anywhere. I just have to add the key anywhere it needs to be written or read.
 
Non-exhaustive list of clues that you should use a class:
1. Your dicts always have the same keys
2. You never loop over the dict
3. You have lots of functions that operate on a dict
 
bingo
 
2:49 PM
Valid rules of thumb. (thumbs?)
 
besides maybe 3, there are a handful
 
A hand full of thumbs... Sounds gripping
 
on the topic of class vs dict... anyone willing to talk about dataclasses? I haven't used, but am trying to find a problem to throw at it to learn what's good
 
I haven't used them much myself, but I imagine the basic use case is "I'm tired of writing __init__ definitions that do nothing but assign self.x = x for half a dozen lines"
def __init__(self, a): self.a = a requires three separate instances of the name "a". But dataclasses only require one -- a: int. A 66% savings!
I unironically appreciate this
 
It's crazy how many libraries are developed to work specifically with dataclasses, instead of supporting any class that has type annotations :|
 
3:04 PM
so this where I hit a wall and am unable to distinguish what dataclass offers that namedtuple doesn't
 
I mean, namedtuple was never the right tool for the job. Unless you actually wanted your class to be a tuple. Which 99% of the time you don't
Person = namedtuple('Person', ['firstname', 'lastname'])
bob = Person('Bob', 'Paddington')

print('Hello'.startswith(bob))  # False
match bob:
    case tuple():
        print('Got a tuple')
Have fun debugging those
 
ok fair
 
Glad to see Ouroboros up and about
 
4:22 PM
Resurrected!
 
 
2 hours later…
6:03 PM
@Aran-Fey I mean, consider the venn diagram of people who appreciate duck typing enough, and are proficient enough with Python internals, to look for a class's __annotations__, vs. people who actively want to use a type checker
@Kevin AFAICT, this is the primary motivating use case, yes.
@Aran-Fey (OTOH, looping over the dict often points towards a list of 2-tuples instead)
 
2-tuples are all you need, really
In all conceivable circumstances
put a 2-tuple inside a 2-tuple, and bam: 3-tuple.
 
6:27 PM
If 2-tuples are all you need, why are you creating a 3-tuple? :P
 
I need little, but I want much
 
Fair
 
In accordance with virtue #1.1 of the Two Great Virtues of Programmers: (Laziness, (Impatience, Hubris))
 
6:41 PM
Shower thought of the day: If god's PC has a von Neumann architecture (as opposed to a Harvard architecture), we might be able to change the laws of physics by moving some atoms around
 
If you're going to try to rowhammer the universe, please do it on a monday morning
That way if you accidentally pop the false vacuum and all matter decays in a blast radius expanding at the speed of light, I'll have maximized my weekends-to-weekdays ratio
 
Deal. On monday morning the universe will turn into flappy bird
 
Acceptable
 
7:33 PM
Phew, after two hours of debugging, I managed to go from "error: an error occurred" to "error: GrommetCollection is empty"
"Contact your system administrator". But doctor, I sob, I am the system administrator
 
7:56 PM
It's telling you to be your own rubber ducky
 
Once I discovered the error's True Name, I could have obliterated it at any time. But first I had to interrogate it to discover how it had hidden from my baleful gaze.
Short answer: try: ... except: pass
 
Ah, the previous sysadmin built it a nice bunker to hide in
 
It looks like they designed a custom error logging system that should write the stack trace to a file before try-except-pass gets ahold of it. But there are scenarios where it goes unlogged. I have sympathy for the previous sysadmin, and will not pursue them with my ClueBat.
 
 
1 hour later…
9:16 PM
stackoverflow.com/questions/73887779 this isn't clear as asked, but based on OP's follow-ups in comments I think it is really just a duplicate of "Q. How do I (do the thing that str.strip does)?".
 
9:47 PM
> My data won't be that complex. It can only be in the form of '(c)'.
Cool, we can use [word[len(word)//2] for word in keywords] then :^)
 

« first day (4365 days earlier)      last day (583 days later) »