« first day (4379 days earlier)      last day (569 days later) » 

1:22 AM
Doesn't seem like it. The top answer implies a feature request
meta.stackoverflow.com/questions/278718/… more general discussion of the topic.
 
 
2 hours later…
3:12 AM
What is the diff between the first one and the second one?
from numpy import random as rnd
print(rnd.randint(10))

import numpy.random as rnd
print(rnd.randint(10))
 
3:27 AM
duplicate stackoverflow.com/questions/55084977 (3.x tag only originally)
@TheRealMasochist The difference is that one of them says from numpy import random, and the other says import numpy.random. They will have the same effect.
You can easily verify this by e.g. using rnd2 for one of the names, and then verifying that rnd is rnd2
 
4:21 AM
@metatoaster the appropriate close reason for copy-paste homework is usually "needs more focus". Please don't imply that the question would be improved by an unexplained code dump (which is how people will react to "needs debugging details")
 
Fair, yeah.
 
4:35 AM
@KarlKnechtel Thank you. :-)
One more question, why does the last one produce an error?
 
That's something else completely different since that's from the standard library, see random.randint.
 
4:51 AM
@metatoaster OK. Thank you. :-)
 
stackoverflow.com/questions/74034049 Do we have anything better for this? What actually is going on; is OP's installation broken somehow?
 
5:06 AM
no, packages that can't bother fixing DeprecationWarning and that thread contains a relevant answer stackoverflow.com/a/73353426
 
@metatoaster but why does it cause an issue on startup?
 
Because it's a readline replacement package for Windows, and part of the installation to make it active is to make it part of site.py, you can see it in the Traceback
been reported for a while, package owner MIA or don't care
Actually, thinking about it I think it should be re-opened and answered
but I need to boot into Windows, ugh
 
5:28 AM
ah.
but then why did it also happen in that beautfiulsoup context? or was that just incidental?
 
6:07 AM
anyone how to use response in js inside a jinja template ?
 
6:28 AM
@KarlKnechtel a bunch of packages (including ones I created/published to pypi) didn't get around to actually fix the import declaration until 3.10 dropped - some of them never actually fix it, like pyreadline
 
7:12 AM
.
 
7:42 AM
@sahasrara62 Do you have an example of what you want to do? This is very vague
 
8:01 AM
basically, api is returning response, and in jinja template i can access that with {{response.abc}} like that. but now thing which i want to work with making charts, so i was thinking if there is way if i can access this response in <script> tag in html in django

first time working on JINJA Templating
 
@sahasrara62 searching for "send value to js jinja" in your favorite search engine should have brought you to this stackoverflow.com/questions/27095329/…
 
8:41 AM
brunch cabbage!
 
9:09 AM
@metatoaster i used that earlier, but giving me undefined in browser console
 
Well, then you did something wrong
 
9:24 AM
this is script i added in html file ,

<script >
var nana = "{{ data|safe }}"
console.log("{{ data.amount }}");
alert({{ data.amount }});
alert("hello world");
alert(nana);
</script>
 
And data is what?
 
@sahasrara62 you set nana as a string, and you never specified what data actually is. Read the other answers too, there is one for JSON, just follow that exactly.
 
9:56 AM
Passing things to JS via template... Looks a lot like my day job
I certify that script as "looks good to me"
 
Wait, really? I'm struggling to think of a data type that would produce sensible output for both "{{ data|safe }}" and {{ data.amount }}...
 
Alright, you got me. My day job's template engine does not have a "|" operator, so I skipped that line.
I'll actually look it up... I see, safe takes a string. And strings don't have an amount attribute. Certainly a problem, as you say.
 
10:11 AM
Oh, it doesn't even auto-convert the argument to string? Welp
 
No clue :-) I was just about to poke through the docs/source to find out
import jinja2; print(jinja2.filters.do_mark_safe([1,2,3])) gives a Markup object whose repr looks like [1, 2, 3]. So maybe it does auto-convert.
 
10:28 AM
I wonder how many websites will go kaboom if your username is </script>
 
thanks all @metatoaster it was same solution as given, issue was with the mock dict i was providing :") , thanks for help everyone
 
 
1 hour later…
11:59 AM
I have a question about the follow Pyhton code using generators.
class MyDataPoint(NamedTuple):
    x: float
    y: float
    z: float

def mydata_reader(file):
    for row in file:
        cols = rows.rstrip().split(",")
        cols = [float(c) for c in cols]
        yield MyDataPoint._make(cols)

with open(fileName) as file:
    for row in mydata_reader(file):
        print(row)
I can use a generator if I have a very large file, so I don't have to read it all into memory and instead only read it line by line, correct?
 
Right
 
But the for row in file line in the mydata_reader is still looping over the entire file
Doesn't that looping mean it requires the whole file to be read into memory?
 
I notice that cols = rows.rstrip().split(",") makes reference to a variable "rows". Where is that variable defined?
 
Or is that for loop actually also a generator, too?
 
for row in file doesn't necessarily read the whole file into memory at the same time
 
12:02 PM
So does that mean the for row in file is creating a generator for file and only yielding one row per iteration?
 
No, but it creates an iterator
Not that it really matters
 
Generator, iterator... To be honest, I often forget the terminology. But I know it doesn't read the whole file at once.
 
Okay, I think that was the misconception that made me confused
Thanks!
 
12:18 PM
Python files are built on top of C files, which are streams. The metaphor to real-life streams is fairly apt. Data trickles into your process at a steady rate, and it doesn't form a build-up on its own.
 
 
2 hours later…
2:39 PM
@KarlKnechtel Sigh, I didn't think so but wasn't sure if I had missed something. Seems like something that should be taken care of sooner rather than later.
 
3:02 PM
How can I use a decorator that belongs to a class attribute?

class Example:
     attribute: Attribute

     def __init__(self, attribute: Attribute):
          self.attribute = attribute

     @attribute.decorator
     def method(self):
          pass

I currently receive the warning message "Local variable 'attribute' might be referenced before assignment". I get why, but what is the workaround for this type of problem? Thanks!
 
That's not a class attribute, that's an instance attribute. You can add self.method = attribute.decorator(self.method) in your __init__
 
Sorry, I meant instance attribute.
And yeah, sure, I could do that, but is there any workaround that enables me to use the decorator like you do usually?
 
Decorators execute before __init__ does, so you won't have access to anything that gets initialized in __init__
 
I see. I'll rethink this then, thanks! :P
 
3:44 PM
Does this look weird?
class Modem(ModemInterface):
    def __init__(self, messager):
        return None
I like it because we load the different modems we have like this:
self.modem = importlib.import_module('monitoring.modems.' + self.modem_type).Modem(self)
and then later in some places I can do if self.modem: self.modem.do_stuff()
 
Definitely weird. Does ModemInterface have an __init__?
 
yes, but it's just: super().__init__(thread_name=name), self.messager = messager
It feels weird, but it also feels very smart :D
 
Assuming both x and y are too long lists. How can I automatically create p?
x = [1,2]
y = [3,4]

p = [[1,3], [2,4]]
 
zip()
 
Why does Modem override the init?
 
3:55 PM
@Kevin OK. Thank you!
 
so that if you select modem None in the ui the modem will become the actual None object, so that I can check with if self.modem
 
It doesn't work like that, if you want Modem() to return None then you have to override __new__
 
I don't get the point of that __init__.
 
ah, ok haha my bad
 
But honestly, I'd just special-case it with an if statement rather than make a fake class that returns None
 
3:59 PM
makes sense
 
The dynamic importing and the design of having many classes with the name Modem is also weird. Dynamic importing is maybe ok if importing all the files is actually a performance problem. But having multiple classes with the same name is a debugging nightmare
 
in a way yes, but it prevents duplication of the name in the file and in the class name
plus then I would have to have many if statements with each their own name, like this I can just call .Modem()
@Aran-Fey also, really? Every stacktrace should show you the file where things happened, making it very obvious what modem we are talking about
 
But every repr will show <Modem object at 0xcoffee>
 
I see, fair point. Where does repr turn up? I mean ofc when I print it, but where else?
 
@Hakaishin you know what they say about being smart when writing code, yeah?
 
4:04 PM
In the debugger also
 
At my day job there are three files that each define their own WidgetService. It's obvious which one is which... In certain contexts. Stack traces are clear enough. But if I'm just writing a note to myself like "todo: refactor WidgetService.frobnitz()", I'll have to hunt through the three files to see which one has a frobnitz that needs refactoring
 
haha, it's been a long time since I could use debuggers :D I always have weird environments where setting up a debugger is a huuuuge pain, so I don't use them too often
@Kevin well make better notes :D
 
I would give the classes unique names and also use those to identify them (instead of the module name). You can manually build a {name: cls} dict, or automagically build it in a __init_subclass__ hook, or you can just loop over ModemInterface.__subclasses__() until you find the class with a matching name
 
And I don't have enough room on my sticky note to write "todo: refactor WidgetLibrary/AppCode/manipulators/frobnitzers/counterclockwiseFrobnitzingWidgetService.cs' WidgetService.frobnitz"
 
@Aran-Fey I'm saving this advice for later, but I'm not convinced yet. I will have to shoot myself a bit before trying that :D
 
4:07 PM
I've tried "refactor CCWFWS' WidgetService.frobnitz" but the meaning of that acronym leaves my memory at least once per day
 
How to get a list of list instead of a list of tuples for p?
x = [1,2]
y = [3,4]

p = list(zip(x,y))
print(p)
 
Try converting tuples to lists
 
I may be a little metaprogramming-damaged. I retract what I said earlier; I do not recommend identifying modems by their class name. Renaming a class shouldn't break your UI, or affect the name that the user sees in the UI. The proper solution is almost certainly to hard-code a {label: cls} dict in the UI code.
 
@Aran-Fey in a way I agree, but then YAGNI
 
Wrongly produced lines.
 
4:19 PM
How are they wrong? What would the correct lines be?
 
It is obvious. 2 points produce a line rather than 2 lines.
A list of lists is expected by plot.
 
The 2 points being what? (1, 2) and (3, 4) or (1, 3) and (2, 4)?
 
look at the signature of plt.plot*
 
@Aran-Fey The latter pair.
 
you'll (hopefully) quickly see that you can simply pass it x and y as two separate params, and it will do the rest
 
4:23 PM
The question is how to produce a list of lists from x and y. Plotting is not the main.
 
if you specifically want to know that, then just iterate and convert the tuples to lists.
 
Obviously
 
[list(whatever) for whatever in zip(...)] or list(map(list, zip(...))
 
Hm. I was expecting there is a simple automatic way. :-)
 
I recommend the solution that doesn't have unbalanced parentheses ;P
 
4:26 PM
^ seconded.
i almost went back to edit..but then left that as an exercise to the reader :P
 
4:42 PM
@ParitoshSingh Thanks.
 
 
1 hour later…
6:10 PM
@Aran-Fey Can you see my question in gitter.im/python/typing maybe? You tend to know alot of things, so if you could take a look and see if you know the solution to my problem, I would be so grateful!
 
Well, I understand the problem, but I'm too tired to think of a good way to explain it
 
Alright, that's fine!
 
The attach method of a Example[Base] instance requires an argument of type Callable[[Base], None], right? But you're giving it an argument of type Callable[[Child], None]. Do you see why this doesn't work?
Your function needs a Child as input. If it gets a Base as input, it'll explode. You need to create a function that accepts Base instances as input.
 
The "callback" should accept any type of child subclass of "Base", but I see what you mean.
It's kind of obvious now when you say it, just need to rethink how I should structure this.
I mean, shouldn't the callback in the "attach" method work with a "Child" also, since it is a "Base" class?
 
Yes. But you have declared that callback works only with Child instances, not Base instances.
 
6:31 PM
How would I then type hint a method with a Callable that accepts Base and all Derived classes?
 
The typing of attach is correct, the problem is the typing of callback
attach needs a function that can be called with a Base as input, but callback doesn't accept a Base as input
Can you see the problem here?
class Parent: ...
class Child(Parent): ...

def child_func(child: Child): ...

child_func(Parent())
 
Yes, I see the problem... hmm..
class Event:
    pass

T_co = TypeVar("T_co", bound=Event, covariant=True)

class EventDispatcher(Generic[T_co]):
    def attach(self, event: Type[T_co], callback: Callable[[T_co], None]):
        pass

class DerivedEvent(Event):
    pass

class DerivedCloseEvent(DerivedEvent):
    pass

def on_close(event: DerivedCloseEvent) -> None:
    pass


dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=DervidedCloseEvent, callback=on_close)
dispatcher.dispatch(DerivedCloseEvent())
This is what I'm actually trying to do.
Is this the only solution?

def on_close(event: DerivedEvent | DerivedCloseEvent)
 
I'll ignore the covariance because I don't want to think about if it's correct. The problem there is that you made the class generic, even though only the attach method should be generic
If I understand correctly, at least
You want to tie together the types of event and callback, right?
I don't see a reason why the whole class has to be generic. Does EventDispatcher[DerivedEvent] mean "this object only dispatches events of type DerivedEvent"?
 
I want to tie together them, but I also want to be able to dispatch all different events of the generic type (e.g., both the DervidedEvent and DervidedCloseEvent)
@Aran-Fey Not exactly, it should dispatch DerivedEvent and all children of that event.
(I've removed "detach", "dispatch" and all other methods in the class in the example)
dispatcher = EventDispatcher[Event]()

^ This should work with all kinds of events.

dispatcher = EventDispatcher[DerivedEvent]()

^ This should work with all events derived from that event.
Is this impossible to do in my example above?
 
6:48 PM
Hmm. I think you would need 2 TypeVars and somehow link them, but this doesn't seem to be possible
E = TypeVar('E', bound=Event)
T = TypeVar('T', bound=E)

class EventDispatcher(Generic[E]):
    def attach(self, event: Type[T], callback: Callable[[T], None]):
        pass

    def dispatch(self, event: E):
        pass
Something like that
The closest thing you can do is probably T = TypeVar('T', bound=Event). Which will incorrectly allow things like
dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(Event, lambda _: None)
 
The issue with the warning still persist though, right? "callback: Callable[[T], None]" will not accept a child of "DerivedEvent" in your example, or am I wrong?
 
You mean the callback function won't accept a DerivedEvent as input, or the attach function won't accept a Callable[[DerivedEvent], Any] as input?
Probably best if you just try it
 
class DerivedEvent(Event):
    pass

class CloseEvent(DerivedEvent):
    pass

def on_close(event: CloseEvent):
    pass

dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=AnotherEvent, callback=on_close)
I mean this above, the first problem I had :P
 
What's wrong with that? I get an error in the attach(...) as expected
That would only be allowed if AnotherEvent was a subclass of CloseEvent
 
class DerivedEvent(Event):
    pass

class CloseEvent(DerivedEvent):
    pass

def on_close(event: CloseEvent):
    pass

dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=CloseEvent, callback=on_close)
I had a typo
I'm still using the wrong class as argument here in the callback method.
But I want to be able to attach all callbacks that has an argument with any of the "Child" events
I'm probably really just confused right now and the solution is perhaps obvious.
 
7:03 PM
@Warcaith No? What's wrong about it? The class accepted by callback matches event, so everything is fine
You're attaching a function that takes a CloseEvent as input to a CloseEvent. Where's the problem?
 
from typing import TypeVar, Generic, Callable, Type

class Event:
    pass

T = TypeVar("T", bound=Event)


class EventDispatcher(Generic[T]):
    def attach(self, event: Type[T], callback: Callable[[T], None]):
        pass

    def dispatch(self, event: T):
        pass


class DerivedEvent(Event):
    pass


class CloseEvent(DerivedEvent):
    pass


def on_close(obj: CloseEvent) -> None:
    pass


dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=CloseEvent, callback=on_close)
Argument "callback" to "attach" of "EventDispatcher" has incompatible type "Callable[[CloseEvent], None]"; expected "Callable[[DerivedEvent], None]"
Why does it work for you? Or what am I missing?
I'm feeling so completely dumb.
 
You omitted the 2nd TypeVar I added
E = TypeVar('E', bound=Event)
T = TypeVar('T', bound=Event)

class EventDispatcher(Generic[E]):
    def attach(self, event: Type[T], callback: Callable[[T], Any]):
        pass
 
I think you forgot to send that (or well, you did send me this):


E = TypeVar('E', bound=Event)
T = TypeVar('T', bound=E)

I didn't change that as you said "but this doesn't seem to be possible". Sorry, just a misunderstanding! :')
It works beautifully now.
 
Ah, I see, I was unclear. My bad. This was supposed to be an alteration of the code above
 
Aaah, I see. Awesome! :)

I'm grateful for all help that you give me. Let me know if I can offer you something. You don't have a tip jar for buying a coffee or anything like that? ;)
 
7:14 PM
Nope. Don't worry about it
 
<3
E = Derived Class
T = Base Class
Right? Just trying to learn what I'm really doing here
Oh, no, the opposite
E = Base Class
T = Derived Class
 
Not sure what you mean? They're both (bounded by) the same class
You need two of them because they have different scopes. E is bound to the class, T is bound to the attach function
 
Oh, I see. But do I need to set what type "T" should be anywhere, or is that automatically resolved by the type hinting when I use the "attach" method?

dispatcher = EventDispatcher[DerivedEvent]() # <- E = DerivedClass
dispatcher.attach( How does this know what T is? )
 
T is automatically inferred by the type checker when you call attach
 
Aaah, alright, that's what was confusing for me. But alright, thanks so much for this, again. :D
 
7:24 PM
Let's also get the variance right while we're at it. Which of these assignments, if any, are allowed?
d: EventDispatcher[Parent]
d = EventDispatcher[Grandparent]()
d = EventDispatcher[Child]()
Presumably the Grandparent one is valid?
 
I see some problem though, for example:

def on_close(event: Event): <- Not a "Child" of "DerivedEvent"
    pass

dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=CloseEvent, callback=on_close)

This is maybe the issue you told me about (Aran-Fey - " I think you would need 2 TypeVars and somehow link them")
 
- Grandparent valid: contravariant
- Child valid: covariant
- Both valid: bivariant
- Neither valid: invariant
@Warcaith That's not a problem though. If the function accepts Event instances, then it can be used for DerivedEvent instances as well. I don't think there's a single type system in this world where that would be a problem
 
EventDispatcher[Parent] should only be allowed, I guess? You should be able to dispatch that "Parent" event both also all "Child" events. "GrandParent" should not be allowed.
@Aran-Fey That's true! :)
 
A EventDispatcher[Grandparent] can also dispatch Parents, right? So shouldn't that assignment be allowed?
After assigning d = EventDispatcher[Grandparent](), what can you do to bring d into an invalid state, where it can no longer be considered a EventDispatcher[Parent]?
 
dispatcher = EventDispatcher[Event]()

^ This should be able to dispatch events that is an "Event" or a child of "Event"

class DerivedEvent(Event):
    pass

dispatcher = EventDispatcher[DerviedEvent]()

^ This should be able to dispatch events that is an "DerivedEvent" or a child of "DerivedEvent"
 
7:32 PM
Sounds contravariant to me
 
@Aran-Fey Well, you could insert "Event" subclasses that should not be handled in this dispatcher. If I have (for a more concrete example), a "EventDispatcher[ReportEvent]", I only want to have events in that dispatcher that are "ReportEvent" specific, if you get what I mean?
It is probably unnecessary to have it in this way, as two dispatcher is kind of the same as a single one in this case.
But well, it helps the users to know which events to expect from a single dispatcher.
 
I'm not sure what it means to "insert" subclasses, but if d is typed as a EventDispatcher[Parent], then your code can only "insert" (whatever that means) subclasses of Parent. And subclasses of Parent are also subclasses of GrandParent. So it should be perfectly fine for d to be a EventDispatcher[GrandParent]
Which would make EventDispatcher contravariant in E
...probably. I'm tired
You can play it safe and leave it at the default (invariant) until you run into problems
 
from typing import TypeVar, Generic, Callable, Type

class Event:
    pass

E = TypeVar("E", bound=Event)
T = TypeVar("T", bound=Event)


class EventDispatcher(Generic[E]):
    def attach(self, event: Type[T], callback: Callable[[T], None]):
        pass

    def dispatch(self, event: E):
        pass


class ParentEvent(Event):
    pass


class CloseEvent(ParentEvent):
    pass


class AnotherParentEvent(Event):
    pass


class AnotherCloseEvent(ParentEvent):
    pass


def on_close(obj: AnotherCloseEvent) -> None:
Mypy informs me that this is an error, but Pycharm doesn't. I guess Pycharms type hinting is kind of buggy.
(I changed so the on_close method uses a completely other parent/child event)
@Aran-Fey Yeah, but I'll investigate this further. :)
 
I had to double-check, but yeah, Pycharm is definitely wrong there
 
Haha, I've learned to not trust Pycharm the last weeks.
MyPy is alot better to double check with.
 
7:47 PM
By the way, if you don't care about the return value of the callback function then you should change that Callable[[T], None] to Callable[[T], Any]
 
Aaah, true. I don't care about it, so that's better. Thanks! :)
I could probably keep weakrefs to the callbacks, if someone forgets to "detach" from the dispatcher, right? :)
 
I don't think that's a good idea. That would prevent people from using a functools.partial as callback, to name just one problem
 
Aaah, so it's better to have an explicit "detach" method like I have right now?
 
Definitely
 
8:02 PM
class Report(EventDispatcher[ReportEvent])
    def __init__(self):
        self.component = Component(self)

class Component:
    def __init__(self, dispatcher: EventDispatcher[ReportEvent]):
        dispatcher.attach(event=ReportEvent, callback=self.method)

    def method(self, event: ReportEvent):
        pass

or


class Report(EventDispatcher[ReportEvent])
    def __init__(self):
        self.component = Component()
        self.attach(event=ReportEvent, callback=self.component.method)

class Component:
Where do you think the responsibility should be here? I'm arguing with myself about this all the time, haha.
 
Depends on context, really. Generally speaking, either one is fine. But if you have a lot of Report classes dispatching lots of different events, then the first one is going to have a lot less boilerplate
...on 2nd thought, that's probably not even true. I'm gonna get some sleep
 
Alright, we'll see what I end up with. I'm just not sure if it's enough to remove (a.k.a. detach) the callbacks for each component in their own del method, as the garbage collector is not running all the time.
But maybe I'm wrong.
Go get some sleep! :D
 
 
1 hour later…
9:17 PM
How to produce random integers between -5 and 5 inclusive but excluding 0?
[rnd.randint(-5,5) for i in range(10)]
 
perhaps make a list of all valid values and then use random choice from that
 
OK. Thank you.
 
a = [rnd.choice([*range(-5,0),*range(1,6)]) for i in range(5)]
print(a)
 
id suggest not cramming so many things in one line. you can create and store the list of valid choices separately
 
9:25 PM
I see. It will increase readability. :-)
 
aye. and in this case, slightly improves performance too because the list doesnt have to be created for each iteration. but even otherwise, readability counts :)
 
Good point. Thanks!
 
10:07 PM
Even though it might be very basic, but I still don't understand. Why the third case does not compile?
from numpy import random as rnd
import numpy.random as rnd # Ok!


from matplotlib import pyplot as plt
import matplotlib.pyplot as plt # Ok!


from sympy.abc import x
# Why can't we write as follows?
import sympy.abc.x # Error!
 

« first day (4379 days earlier)      last day (569 days later) »