« first day (4364 days earlier)      last day (574 days later) » 

12:20 AM
Is it weird if I have a multiple folders as modules and py file inside and I try to import the main.py(in root dir) inside of these modules? For type hinting purposes only
 
12:46 AM
265
Q: Python type hinting without cyclic imports

velisI'm trying to split my huge class into two; well, basically into the "main" class and a mixin with additional functions, like so: main.py file: import mymixin.py class Main(object, MyMixin): def func1(self, xxx): ... mymixin.py file: class MyMixin(object): def func2(self: Main, ...

 
 
1 hour later…
2:14 AM
@metatoaster Cool, will read. FWIW, I don't have cyclic imports. But it gave me idea to move all utility classes to a different folder than main.py
 
yeah, that thread did encompass what you may have tried to do
 
 
3 hours later…
5:38 AM
@KarlKnechtel that tuple subclass question further make me question why I put so much effort writing answers for a language feature that I absolutely not care about, though the frustrations really drive home how I feel right about moving on from Python (also do read my answer if you find the time - it's surprising how bolted on the whole type hinting system feels)
(since you did try to help)
 
 
2 hours later…
7:41 AM
@Warcaith ah, just curious but did you benchmark it as you mentioned last time? just curious since I may do that kind of generating HTML later on for some projects.
 
8:30 AM
Cbg everyone
 
8:45 AM
Cbg
 
 
4 hours later…
1:12 PM
Nullish coalescing does not really exist in python
But what is the preffered way to run a method on the object if it is optional?
 
@Warcaith I mean, there the or operator: stackoverflow.com/a/4978745/12349101
 
if self._file:
    self._file.close()

or

self._file or self._file.close()
Yeah, I know, so the "or" is not a "hacky way" doing it?
 
Definitely option 1
 
"Explicit is better than implicit" - Tim
 
@Aran-Fey The reason for that is that it's a bit clearer?
 
1:14 PM
it's not that it's hacky, it's that it isn't as explicit/detailed compared to if block
 
Yeah, I see :)
 
@Warcaith I think you mean a lot clearer
 
@Aran-Fey Mega ultra clearer*
if self._file not None and isinstance(self._file, TextIO):
    self._file or self._file.close()
What about this? ;)
 
Looks like a syntax error to me
 
Maybe
 
1:17 PM
@Warcaith 3 people armed with an axe would like to know your location
 
@Aran-Fey Ouch!
 
Clarification. I'm not saying "haha, this is so un-idiomatic that I'm jokingly implying it won't run", I mean "this won't run because x not None isn't valid syntax"
 
@Kevin I know, "x is not None" is more correct, right?
Or does that even work?
 
I often use "not x"
 
1:18 PM
It's more correct in the sense that x not None is 0% valid syntax and x is not None is 100% valid syntax
 
@Warcaith btw, if you want to do this without depending on if block: stackoverflow.com/a/16247152/12349101
 
I usually avoid these kinds of situations by only assigning None to values in limited and controlled scenarios
If a function might return None, I'm probably not going to call it without checking its result on the very next line. There aren't many scenarios where I need to know if self.file is None or not, and the line responsible for making it None is far away, off my screen
 
unrelated: does anyone know of any ways to convert tkinter's grid row, column values to tkinter's place x, y ones? I kind of managed to do it for Label widget using fixed sized text, but that's it (looked around and I don't think anyone has ever asked a question related to that on SO before)
 
I imagine there's quite a lot of math involved
 
dpaste.org/v2Fcb works in calculating the place's coordinate using the font measurement, but only using default font size
yeah, same :/
I only want to do this for Label widget though, so I'm guessing it will be less hard than if I were to do it for everything else
 
1:26 PM
If it was guaranteed that every widget (including widgets that can contain widgets) has exactly one preferred size that precisely fits everything it wants to display, then you could determine the width of each grid column and the height of each grid row by finding the maximum size of each widget in that column or row.
Then you can use cumulative sums to calculate the x and y offset for each column and row, and call .place manually on each widget.
 
one way I thought of doing this was to find a way to get every coordinate allocated by a tkinter instance, whether it's using place or grid, (eg: map of the used "surface"?) and then convert them one by one, but don't know how to do that either
 
If any widgets span across multiple rows or columns, I don't know how to handle that
 
@Kevin yeah, but as the example I posted show, I don't know which values the place's coordinate correlate to, so had to test with the font's size to see if it works (which it does, but only on default size, since I tried on custom size and then it stopped working as expected)
@Kevin me neither :D
how much downvote will I have if I post this on SO? maybe using "How to convert place coordinate to grid row and column?"
 
@Kevin What about a class that opens and closes an internal file? You don't want to close a file if it never has been opened?
 
@NordineLotfi You'll probably get a lot of comments like "why do you want to do this? You should almost never use the place geometry manager". Some of them might downvote you if you don't give them a good reason.
 
1:31 PM
yep, that's exactly what I predicted too :/
 
Or, hang on. convert place TO grid? I think that's just impossible.
As a simple example, you can use place to make two widgets completely overlap (I think). grid won't allow that.
@Warcaith I'd probably use a with block. I'd make the entire class a context manager, if necessary.
 
@Kevin even if you take into account whatever it is that make the place coordinate the size it is (taking into account that one does not override any size values except font size)?
if I knew what make it tick, I could do it I think, even if it's gonna be harder for any other widget, for Label it should be possible
 
@Kevin Hmm, that's true. Do you have any good tutorial about making a great context manager perhaps? :D
 
I basically just read docs.python.org/3/library/… and think real hard about it
 
@Kevin Would it be okay to support users to use the context manager with "with", but also make them able to open and close manually?
 
1:37 PM
Sure, if you're willing to put in the extra effort. I am usually not willing.
@NordineLotfi converting grid calls into equivalent place calls: possible. converting place calls into equivalent grid calls: impossible.
 
How would you structure this types of classes if the "Report" class needs to be able to get the path from the HTMLLogger? (This is a really minified version of something I'm experementing with atm)
class Logger(ABC):
    @abstractmethod
    def log(message: str):
        pass

def ConsoleLogger(Logger):
    def log(message: str):
        # Write to console


def HTMLLogger(Logger):
    def log(message: str):
        # Write to HTML file

    def get_path(self) -> Path:
        # Get the pass to the HTML file

@dataclass
class Report:
    _loggers: list[Logger] = field(default_factory=list)

    def __post_init__(self):
        self._loggers.append(Console.Logger())
        self._loggers.append(HTMLLogger())
 
@Kevin I mean, I also thought that doing the reverse would be complicated. For example, here the equivalent example using grid, for the link I posted above: dpaste.org/DDAat
here, by passing to an imaginary function that would do the reverse, I would be able to know that if column is 0, then it's at that side of the tkinter window, and just need to know which one goes after/before which in term of position
 
@Warcaith Sounds like a design failure to me. If Loggers don't have to have a file path, what business do you have trying to access it? But if you're sure you want to do it, just do if isinstance(logger, HTMLLogger): path = logger.get_path()
 
1:52 PM
@Aran-Fey Yes, it is a design failure for sure, trying to fix some things that are kind of odd in the C++ implementation of the same interface.
 
If HTMLLogger's one and only responsibility is to write HTML to a file, then I would not allow an HTMLLogger to be created unless a valid file handle is passed to its constructor
 
But yeah, the thing with that is that a user would want to know where the HTML file was generated via the report. I should perhaps not decouple it to a separate logger.
@Kevin So you keep that responsibility to the report in this case, right?
 
Perhaps. I would also be willing to have a default path that the HTMLLogger uses if no file is passed in.
I'm less interested in "responsibility" and more interested in "invariants". I want to uphold this invariant in 100% of cases: if the HTMLLogger exists, its file attribute is an open file object.
 
The report will need to write to a HTML file, a custom file used for gathering filepaths, but in the future also output the logs to a database, which is why I wanted to decouple everything from the Report class (as it gets messy very fast).
Everything is in the whole Report class in the C++ implementation :|
 
I'd take the decoupling a step further and have no logger-related logic in the Report class, other than keeping a logger attribute, and calling logger.log(whatever)
You could still log to multiple locations and output formats if you create a composite logger
... Or possibly Python's built-in logging architecture can already do composite-like logging, out of the box. It sounds like something the devs might have implemented
 
2:05 PM
The logging will be pretty advanced with custom objects, so no simple strings, but I'll be investigating both the composite logger and the built-in logging mechanism
 
@NordineLotfi Here is what makes it tick: github.com/tcltk/tk/blob/main/generic/tkGrid.c. Do not be afraid. I believe you can find insight here, even if you don't know C. Just reading the function names and comments can give you ideas.
Ooh, they have a term "slot" which can refer to a row or column. I will steal* this word for my own grid-having projects. (*insofar as I can do so while still adhering to the licensing terms)
 
@Kevin :o Thanks! I usually immediately jump into Cpython repo for those kind of problems but never thought of looking at the tkinter's repo...
 
2:21 PM
Yeah, you won't find much bare-metal GUI code in the CPython repo. Python and Tk/Tcl are controlled by entirely separate entities, so their code bases are cleanly separated
... Which is the reason for some of Tkinter's quirks. Gotta use a lot of crazy glue at the seam where the two projects join
 
yep, and also tcl + python contribute to make the glue weirder
one nice thing about python is that you can make a very bare metal GUI on Linux using just ctypes and the xlib local libraries (not to be confused with the related Xlib module). On windows though? I think it could be possible but I honestly don't know how to do that there (although I'm using Win10 as I say this)
 
I did a moderate amount of GUI work back in the Windows XP days, using C++. You could create a basic window with maybe... 20 lines of code? I imagine the same approach works today, since MS is fairly diligent about backwards compatibility. And Python can do anything that C++ can do, although it might take more than 20 lines.
 
3:00 PM
morning cabbages, folks!
 
 
1 hour later…
4:26 PM
My computer has become ridiculously slow after preserving console logs for debugging purposes on Chrome. Any tips to fix this?
I tried clearing the cache, but to no avail.
 
Close chrome. if that doesn't work, terminate all chrome-related process in task manager. If that doesn't work, reboot. If that doesn't work, wipe hard drive and reinstall OS
 
4:42 PM
Dangerous advice
 
True, there might be a rootkit trojan still hanging around. Remove hard drive, bore a hole through it with a power drill, and buy a new hard drive
 
And I was about to suggest that they use a dry soft piece of cloth for wiping
 
Steel wire would get those stubborn ones and zeroes more effectively
 
5:02 PM
The only way to make sure that no malicious data remains is to set every bit in your memory to 0.5
 
My hardware is malice-proof because instead of using bits that represent True and False, my bits represent Beautiful and Ugly.
Most malware is built upon lies and deception, so it stands to reason that they can't operate on a system with no native concept of truth
I speculate that a determined adversary could deliver a devastating payload of ugly truth to me, but this has not yet happened. Neither a broad truth, such as "many people have no access to clean drinking water", or a personal truth, like "you can never take back that hurtful thing you said in fifth grade"
 
5:47 PM
Thanks @Kevin, it worked
 
5:57 PM
Oh good. Usually when a program uses a ton of memory, things go back to normal once it's done. Sometimes you have to use the "I wasn't asking" stick
 
6:30 PM
anyone know of a tool that can scan my requirements.txt and my repo to tell me what I have in my requirements.txt that I don't use? deptry seems to be written in py2k and pip-extra-args has too many false positives
 
Just work the other way round and use pipreqs to write it for you?
 
ooh! thanks
@roganjosh negative. pipreqs didn't migrate to py3k :(
 
Wut? I use it all the time
 
tree = ast.parse(contents)
  File "/home/username/.pyenv/versions/3.8.6/lib/python3.8/ast.py", line 47, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 2
    print add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False)
          ^
SyntaxError: invalid syntax
 
But that is a syntax error in Python 3?
The code you're running is written in Python 2. That error has nothing to do with pipreqs but the interpreter you're invoking (which is the correct, Py 3, one)
 
6:37 PM
I get that when I run pipreqs ., and the offending line is not my code (seems to be thrown by ast.py on an unknown file, which is even more bizarre).
 
Can you dump the full traceback into a dpaste or something?
 
I suspect the file is unknown because whatever called compile didn't provide a useful string to the filename parameter
 
$ pipreqs .
ERROR: Failed on file: ./.test/lib/python3.8/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py
Traceback (most recent call last):
  File "/home/username/workspace/repo/.test/bin/pipreqs", line 8, in <module>
    sys.exit(main())
  File "/home/username/workspace/repo/.test/lib/python3.8/site-packages/pipreqs/pipreqs.py", line 488, in main
    init(args)
  File "/home/username/workspace/repo/.test/lib/python3.8/site-packages/pipreqs/pipreqs.py", line 415, in init
@Kevin I wanna agree with this
 
>>> compile("print add_code_to_whatever()", "wouldn't you like to know ;-)", "exec")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "wouldn't you like to know ;-)", line 1
    print add_code_to_whatever()
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
>>>
A demonstration of an unhelpful file name
 
yeah, agreed. Someone over at pipreqs left that parameter blank
 
6:43 PM
Confident that their code would never fail, no doubt
I like that hubris. Give them a raise, whoever they are.
If I can remember where I keep my site-packages, I will poke around
 
Is .test your virtualenv? Why is pipreqs trying to process a site-packages directory?
 
./.test is my virtualenv
 
I think get_all_imports looks at all your import statements, and opens every file you're importing, and looks at all of their import statements, and so forth. So it could crawl to some unusual places.
In any case it would probably be good to inspect ./.test/lib/python3.8/site-packages/debugpy/_vendored/pydevd for 2.7-only syntax
 
stands to reason
 
I've rapidly got very lost on this. Where does that path come from, @Kevin?
 
6:51 PM
At the top of the inspector's most recent stack trace.
I didn't see it myself until I looked at pipreqs.py and saw its try-except had logging.error("Failed on file: %s" % file_name)
"Boy, it would be useful if that executed in this particular scenario... Oh, it is executing."
Oops, just noticed I didn't copy-paste the full file name. Correction: it would probably be good to inspect ./.test/lib/python3.8/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py
I thought it was weird your file didn't have an extension, but I'm not a cop
 
pipreqs processes every single python file in your directory (and subdirectories). Which is... let's say... less than smart. Give it the path to your code
 
I gave it too much credit :-)
Bulletproof import tracing would be Halting Problem Hard anyway
 
Why should it not do that, though? This is suggesting that there's legacy python stuff hanging around in the package dir?
 
While it is useful to have a tool that finds legacy cruft in one's site-packages directory, it's not what I expected this tool to do. Not that I have very clear expectations, as I am only half paying attention.
 
I could imagine you might want to bundle in some perfectly-fine Py2 server/process that you could launch from the CLI of your actual Py3 package
 
6:58 PM
A valid use case, yet difficult
 
I think I'm inclined to go easy on pipreqs here since it's a convenience that tries to help you out. And based on this discussion, I'm not entirely sure that the other two such tools wouldn't have been dismissed as not ready for Py3 through a similar issue
 
@roganjosh I don't know where the python2 code is coming from, but a tool that defaults to your current working directory probably shouldn't process every single python script it can find. That's just asking for something to explode. You can have tests, virtualenvs, a sphinx config, and god knows what else in there
 
If I were king of all programming languages, I probably would require Py3's compile to work on Py2 code. The developers would receive a bag of silver coins for the extra effort, of course.
 
ok, pipireqs finds valid packages, but it does miss some packages, which is... less than ideal. I think I've created an XY problem. So here's more information:

I'm working on a PR. OP (left the org) submitted a garbage requirements.txt that includes unnecessary stuff (like jupyter, which they were using locally but is not necessary for anything that's happening here). I now want to prune away useless packages. Not the biggest deal - requirements.txt has 170+ lines. But I'm also an idiot and wasn't diligent in pruning requirements.txt in past commits. This has gone on for like a year, so th
 
@Aran-Fey Then its only crime is defaulting to anything? The arg is pretty clear
Poor pipreqs - tough crowd
 
7:01 PM
I don't think that's clear. I'd honestly assume that you're supposed to run it on your project directory, not your code directory
 
If the inspector's current working directory was his site-packages directory and he ran pipreqs ., then I will not charge pipreqs with a crime.
 
Usually when you run a tool like this - pytest, tox, poetry, etc - you do it from your project directory. I don't think it's smart to have defaults that go kaboom if your tool is executed in the project directory
 
I wouldn't be running it inside site-packages at all, does it suggest it's for that? It's for your actual project repo, not the installed version
 
If his current working directory was a sensible project root directory, which happened to contain a venv directory with its own site-packages... I may charge pipreqs with misdemeanor public nuisance
 
^ that is what happened
 
7:06 PM
Many factors are at play. I will consider them deeply in my judge's chambers. I will not be napping.
 
@inspectorG4dget Sounds better than finding too many dependencies tbh. If it doesn't miss all too many, it shouldn't take too much effort to add them by hand?
 
@Aran-Fey that's fair. I think I'll just prune the obvious ones and brush off the problem for later
 
If you really do want to scan your site-packages, I think there's an ignore_errors flag you can set so it will keep going despite encountering that one 2.7 file
 
I'm glad I was able to mount at least a partial defence for pipreqs. It's still my friend :P
 
I'll give that a shot. Thanks
 
 
1 hour later…
8:15 PM
switching gears to code style on imports:

PEP8 doesn't say how I should order `import ...` and `from ... import ...` statements? Do the `from`s go in a separate block?
 
Huh, I thought PEP 8 said to separate them. I always put the from imports after the other imports
Sometimes with a blank line inbetween, sometimes not. Depends on how I'm feeling that day
 
super! thank you :)
It does look a lot cleaner that way
 
8:32 PM
I've mostly stopped worrying about organising imports.
There's typing, then standard library, then third party, then internal.
No alphabetic order or based on type.
 
8:53 PM
heh. I go the other way around, but yes.
 
9:24 PM
Hellooo. Here I am agaiiiin. :')

Sooo, how would you design this type of code?

The class should:

* ... be able to write "LogEntries" to a text file.
* ... be able to expose the path to the text file.
* ... be able to write "LogEntries" to a HTML file.
* ... be able to expose the path to the HTML file.
* ... be able to write "LogEntries" to a database.

All of the "write" operations should happen through a simple "log" method, but I want the user to be able to know where these files are written on disk also, which means that a simple "adapter/logging pattern" isn't enough. There must be s
 
Doesn't the logger.attach(HtmlWriter('foo.html')) design solve this just fine? The user can grab the file path from the HtmlWriter. If you want to make this easier, you could do something like logger.html_writer = HtmlWriter('foo.html') instead
Or just logger.html_file = 'foo.html'
 
Do people really need to get the path to the text|html file? What's the usecase for that?
Either way, those should be three classes – one for each output type – and every one of them should have just one location/destination/URL (choose appropriate name) attribute.
 
@MisterMiyagi They won't need it, but it's one of the requirements for our "Report" class. I don't think anyone going to use it (as the framework will provide the outputs automatically when all of the tests ends), but I still want to support it.
I'll try to implement something and send it here, with help of your suggestions. Could you perhaps give me feedback later?
It's always hard to get it right the first time :p
 

« first day (4364 days earlier)      last day (574 days later) »