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

01:22
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…
03:12
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))
03:27
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
04:21
@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.
04:35
@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.
04:51
@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?
05:06
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
05:28
ah.
but then why did it also happen in that beautfiulsoup context? or was that just incidental?
06:07
anyone how to use response in js inside a jinja template ?
06:28
@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
07:12
.
07:42
@sahasrara62 Do you have an example of what you want to do? This is very vague
08:01
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/…
08:41
brunch cabbage!
09:09
@metatoaster i used that earlier, but giving me undefined in browser console
Well, then you did something wrong
09:24
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.
09:56
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
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
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
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
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
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…
14:39
@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.
Anonymous
15:02
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__
Anonymous
Sorry, I meant instance attribute.
Anonymous
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__
Anonymous
I see. I'll rethink this then, thanks! :P
15:44
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?
15:55
@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
15:59
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?
16:04
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
16:07
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.
16:19
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
16:23
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
16:26
^ seconded.
i almost went back to edit..but then left that as an exercise to the reader :P
16:42
@ParitoshSingh Thanks.
 
1 hour later…
Anonymous
18:10
@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
Anonymous
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.
Anonymous
The "callback" should accept any type of child subclass of "Base", but I see what you mean.
Anonymous
It's kind of obvious now when you say it, just need to rethink how I should structure this.
Anonymous
18:22
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.
Anonymous
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())
Anonymous
Yes, I see the problem... hmm..
Anonymous
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())
Anonymous
18:37
This is what I'm actually trying to do.
Anonymous
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"?
Anonymous
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)
Anonymous
@Aran-Fey Not exactly, it should dispatch DerivedEvent and all children of that event.
Anonymous
(I've removed "detach", "dispatch" and all other methods in the class in the example)
Anonymous
18:43
dispatcher = EventDispatcher[Event]()

^ This should work with all kinds of events.

dispatcher = EventDispatcher[DerivedEvent]()

^ This should work with all events derived from that event.
Anonymous
Is this impossible to do in my example above?
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)
Anonymous
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
Anonymous
class DerivedEvent(Event):
    pass

class CloseEvent(DerivedEvent):
    pass

def on_close(event: CloseEvent):
    pass

dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=AnotherEvent, callback=on_close)
Anonymous
18:58
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
Anonymous
class DerivedEvent(Event):
    pass

class CloseEvent(DerivedEvent):
    pass

def on_close(event: CloseEvent):
    pass

dispatcher = EventDispatcher[DerivedEvent]()
dispatcher.attach(event=CloseEvent, callback=on_close)
Anonymous
I had a typo
Anonymous
I'm still using the wrong class as argument here in the callback method.
Anonymous
But I want to be able to attach all callbacks that has an argument with any of the "Child" events
Anonymous
19:02
I'm probably really just confused right now and the solution is perhaps obvious.
@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?
Anonymous
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)
Anonymous
Argument "callback" to "attach" of "EventDispatcher" has incompatible type "Callable[[CloseEvent], None]"; expected "Callable[[DerivedEvent], None]"
Anonymous
Why does it work for you? Or what am I missing?
Anonymous
I'm feeling so completely dumb.
19:07
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
Anonymous
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! :')
Anonymous
It works beautifully now.
Ah, I see, I was unclear. My bad. This was supposed to be an alteration of the code above
Anonymous
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? ;)
Nope. Don't worry about it
Anonymous
19:14
<3
Anonymous
E = Derived Class
T = Base Class
Anonymous
Right? Just trying to learn what I'm really doing here
Anonymous
Oh, no, the opposite
Anonymous
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
Anonymous
19:20
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
Anonymous
Aaah, alright, that's what was confusing for me. But alright, thanks so much for this, again. :D
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?
Anonymous
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
Anonymous
19:27
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.
Anonymous
@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]?
Anonymous
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"
Sounds contravariant to me
Anonymous
@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?
Anonymous
19:34
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.
Anonymous
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
Anonymous
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:
Anonymous
Mypy informs me that this is an error, but Pycharm doesn't. I guess Pycharms type hinting is kind of buggy.
Anonymous
(I changed so the on_close method uses a completely other parent/child event)
Anonymous
19:42
@Aran-Fey Yeah, but I'll investigate this further. :)
I had to double-check, but yeah, Pycharm is definitely wrong there
Anonymous
Haha, I've learned to not trust Pycharm the last weeks.
Anonymous
MyPy is alot better to double check with.
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]
Anonymous
Aaah, true. I don't care about it, so that's better. Thanks! :)
Anonymous
19:56
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
Anonymous
Aaah, so it's better to have an explicit "detach" method like I have right now?
Definitely
Anonymous
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:
Anonymous
Where do you think the responsibility should be here? I'm arguing with myself about this all the time, haha.
20:06
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
Anonymous
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.
Anonymous
But maybe I'm wrong.
Anonymous
Go get some sleep! :D
21:17
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
21:25
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!
22:07
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 (794 days later) »