#voice-chat-text-1
1 messages ยท Page 32 of 1
Do you have a coding question?
@proper ridgenot today bro
for the next two weeks, you can use text instead of voice for communication
@proper ridgewhere rus phyton community?
Rust Python community?
AHhahaha. russian
Ah that makes more sense. I don't know, actually. There must be, but I haven't had anyone mention one before
@mild flume
maybe you should create a Russian chat?
Why russian?
We stick with English since we can really only moderate languages we know. And since most commands/functions/etc. are in English for programming, that ended up being the most reasonable option
learn English, it's useful for programming in general
But if you do find a Russian Python server, please let me know! I like finding other resources I can potentially recommend to people
there is some community that can be found thorugh Discoverable Servers but it's sketchy
Fair
with scam messages all over it
Lame
How is All?
Hanging in there. You?
@zenith wedge When you were mentioning wanting breakfast stuff, this came to mind: https://youtu.be/EHIHl8Rw6W8?si=YKzDl024RDYj0QNO
Full breakfast, The Full English, The Big Breakfast. Unless you are running a double marathon, you absolutely don't need one.
Me Profile on Spotify - https://open.spotify.com/artist/0hQBk...
Itunes/Apple Music - https://music.apple.com/au/artist/tom...
Bandcamp - https://tomcardy.bandcamp.com/album/a...
Merch - https://tomcardy.bandtshirts.c...
The Python Software Foundation
Not for profit
Actually is there a difference between not for profits and non-profits?
Or are those just two phrases for the same thing
Yep, Excel is going to have native (well relatively native) Python useage
It's.... odd
How to use django in python
Some are just here as individuals, we do have a few on staff
We are not run by the PSF
We're a separate entity
We have worked with them and hosted some launch parties and a code sprint
Scotch,Spliff & Ice
Is Mysql Mandatory for Web application making in python
But we are not officially a part of the PSF
Good to hear mate, hope you well
I was also able to find some terrible Python-related Telegram channel
(the author is funny though)
Not sure
Terrible as in just poor quality?
No, not at all
terrible as in his joke taste
I wanted to see if we were part of PSF.
Was thinking of proposing sth.
Scotch,Spliff&Ice
Hit the city, hit the dice
Don't forget the slice...
Could we do...a python course with some of PSF being guest speakers?
If we use django in python , as a framework, can we use HTML and Javascript Front end in VS.Code to do coding furtheras a static page...
You don't have your move your hand to move the cursor
That's the one I use
You just use your thumb to move it
you'll be dealing with HTML anyway
Trackballs have been around for ages
Django does not prevent usage of JS on the frontend, although composing front-end frameworks with Django's templating is non-trivial
Not only that, you don't have to have it on your desk
You can have it just sitting in your lap or wherever
often if you're building a complex enough front-end application Django will end up just handling API stuff
@delicate wren Python is a backend, But Html and Javascript is front end, im confused...
Javascript also has engines to act as a backend
Most common one being Node.js
Front end for web is made of 3 pieces: HTML, CSS, and JavaScript
mostly
HTML tells the browser what to put on screen, CSS tells it how to make it look, JS handles interaction and other stuff
@zenith wedge Your mom?
It's weird setting up a Dell machine
We've had only HP for ages
Django on its own does not provide any front-end interactivity as far as I know
Could the server become a part of this list?
https://www.python.org/psf/fiscal-sponsorees/
They're all communities dedicated to python.
We're already listed as a recognized community on their site
3rd column, last row
Scotch,Spliff&Ice
Hit the city, hit the dice
Don't forget the slice...
Large extra small,
Can't do it in public, can't do it at all
Enough to Stumbling
Weak be crumbling
Aren't no stunting
Tryk den Kobling
Vi OG...
@pseudo raven I guess I count as not normal, then
Ohh I see.
I was thinking of hosting some courses, hackathons, etc. to engage more with the community.
@pseudo raven Tell that to light sleepers
Like what IBM does. They host events here and there as short courses with guest speakers, teach some stuff through code, and that's it. They've been getting their community through these.
And that's one company with one package. We'd be representing python itself, and could host events like those as domain-specific use-cases.
We do Code Jams and Game Jams
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
Ohh very nice.
@pseudo raven also that's why many cars now have fake engine sounds to make them louder
@pseudo raven I've never heard that phrase before
"IF you put something on internet, it's there forever
No it's not there forever
It's there as long the computer you put it on, is turned on
If Facebook/Meta turn off their PC, it's not there anymore
So you rely on somebody else...
It's all about DNS>..
That's great
Better to assume that it will be there forever. Helps encourage people to not put stupid stuff or potentially dangerous stuff out there
By dangerous I mean things that would help people track or blackmail them
For sure
Or i don't know
Because you make people stupid
But i can understand the perspective
How does that make people stupid?
That encourages people to think twice before posting things
If anything that's making them slightly wiser or at least better informed of the dangers
If minority is smart, then majority must be stupid, but you don't have to make people stupid
Unaware, misguided then
because it's incorrect
Factually? Yes. Practically? No
You tell someone that "no, that's not actually the case", a lot of people will go "oh, then I don't have to worry"
That's counter productive if you're still trying to get them to be smarter about their online presence
Isn't unawareness the issue to begin with?
True
But it's missing the forest for the trees
The big picture is make people be careful
yes I do
I can see it, i don't know
Just wanted to say it ๐
Oh for sure
Source code: Lib/unittest/__init__.py
(If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.)
The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.
To achieve this, unittest supports some important concepts in an object-oriented way:
it's okay
!paste
test_init is wrong
Yeah, I've been trying to see how to properly test initialization.
generally you should be testing behaviours/scenarios/usecases not methods
state what you assert in the test name
(if possible)
Expect test names to be long and descriptive
if you want to test __init__, check invariants (if any)
I mean we define how the object behaves by testing if the methods that manipulate it are working properly.
if your __init__ just assigns data, there isn't really anything to test
So, I just want it to see if it raises an error when creating an instance.
if __init__ does conversion and/or validation, test those specific things not initialisation in general
It shouldn't raise an error.
Yeah I'm testing those individually.
Then you're covered
it can
test when it does
and when it doesn't
Could you kindly have a look at how I've written the testers? Is it terrible or does it have some chance of redemption hehe.
Yeah been adding fail cases into my testers.
what you're testing there isn't "can initialise an object"
what you're testing there is "can initialise an object given non-numpy list"
I need to get a small dock for these laptops that I can use to plug in ethernet
so you're testing the conversion
Drives me bonkers that laptops don't have that port anymore
which can (and will) at times fail
And the wifi connection here is so friggin' bad where I'm at
Which tester are you referring to?
I'm the furthest away from our access point in the office as i could be
And I'd rather not have to tether my phone
example: give it the wrong type
Data("abc") is expected to raise an exception
no assertions after .pad()?
https://paste.pythondiscord.com/ATRA#2L88-L111
I'd hope not
No.
Unless you add errors like I am manually doing.
Fair
A bit of a defensive coding which Mr. Nedbat said not to do, but I think this one is justified?
Still a bit hard to distinguish fool-proof vs defensive.
sounds like check_padding should be called there
Remember "Python is a language for conscenting adults". There's only so much protecting you can do/should need to do for the users of your library. If they aren't reading your docs and handling the types properly, that's partly on them
Over checking can affect performance
neither of Datas, that .pad() was called on, have any assertions afterwards
missing assert matrix.padded seems like
wait
oh
assert deez_nutz
yeah, just call it again
after second
yeah, assert that it doesn't break it
@proper ridge
does .pad() on padded keep the data as is?
then make a copy of data
and compare afterwards
for exact equality
coverage isn't good enough metric
tests still need to make sense
while you're doing that you might also define .__eq__ and .copy for Data if not defined yet
This laptop dropping WIFI is going to get reeeaaaally old reeeeaaallly fast
it's okay but it's not the only thing that tests should be aiming for
# how to split these -- that's a separate question
assert Data([1, 2, 3]) == Data([1, 2, 3])
assert Data([1, 2, 3]) != Data([1, 2, 4])
original = Data([1, 2, 3])
assert original.copy() == Data([1, 2, 3])
assert original == Data([1, 2, 3])
depends
whats the point of vector calcs?
AI/ML, data representation, Quantum Computing
class Vector {
// Constructor method to initialize the vector components
constructor(x, y) {
this.x = x;
this.y = y;
}
// Method to add another vector to the current vector
add(v) {
return new Vector(this.x + v.x, this.y + v.y);
}
// Method to subtract another vector from the current vector
subtract(v) {
return new Vector(this.x - v.x, this.y - v.y);
}
// Method to multiply the vector by a scalar value
multiply(scalar) {
return new Vector(this.x * scalar, this.y * scalar);
}
// Method to calculate the dot product with another vector
dot(v) {
return this.x * v.x + this.y * v.y;
}
// Method to calculate the magnitude (length) of the vector
magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
// Method to normalize the vector (make its magnitude 1)
normalize() {
const mag = this.magnitude(); // Get the magnitude of the vector
return new Vector(this.x / mag, this.y / mag); // Divide each component by the magnitude
}
}```
like why did i make this class to do my math for me, i feel like its extra work
It's good practice.
def test_copy_leaves_original_intact():
original = Data([1, 2, 3])
original.copy().normalise()
assert original == Data([1, 2, 3])
and i barely end up using it for its intended purpose
thing
I bought one because my laptop has very little in terms of ports too
only a single USB Type-A
thats why i have a tower, i have like 6 usba 3 ports and then a pcie card which gives me 4 more
guys
yes?
on the new computer I have 9 Type-A ports, of which I use 0
any clue on how to setup poetry + django ?
I'd expect it to be not that different from other poetry projects
is there a specific issue?
i use vr, and vr takes up 8 ports which only leaves 2 usbA ports for my computer(sad moment) but luckily i have two usb-c ports for other things
basically the structure. Im trying to follow the Django Tutorial. Using its CLI it will set up a structure for you, but then if you try to follow with poetry the structure starts to mess up quickly
there is some random blog post which explains just that
https://builtwithdjango.com/blog/basic-django-setup
I haven't checked it for myself, but that's something I'd probably use for guidance
they do poetry stuff first, and only then run django-admin startproject via poetry
okay it seems promising, ty Alisa!
@proper ridge class is more common
with test-class-per-code-class, since ideally classes should be usable (and therefore testable) in isolation
which isn't always the case
@delicate wren look i got it to work
sometimes there may be a test scope that involves multiple classes, modules, etc.
with the difference being poetry run django-admin.py startproject project_name . (. there says to start in an existing directory, if I understand correctly)
does pytest allow inline tests? (inline with the rest of the code)
from what I remember seeing with both Python and C# testing, they have tests as some outside module/package
@delicate wren Do u use Poetry in your daily basis by any mean?
no
I've stopped working on Python projects as seriously around the time setup.py officially died, iirc
or not "died" just got labelled as non-preferred
direct use of setup.py and distutils are deprecated though
whereas in 2020~2021 distutils was okay-ish for doing C dependency compilation afair
where embed
(the title of the page has a question mark at the end, which is not reflected in the URL)
the latest Python project, that I work on and which is considerably serious, does not involve me using poetry or whatever else because there aren't really any pypi dependencies to manage there
with this being the only mention of versions on Python's side
[build-system]
requires = ["maturin>=1.0,<2.0"]
build-backend = "maturin"
poetry seems useful for poetry.lock
but now there are other project/dependency management tools that have lock files too
pipenv does, pdm does
rye too
I don't remember which others exist
django_tutorial/
โโโ db.sqlite3
โโโ django_tutorial
โย ย โโโ __init__.py
โย ย โโโ __pycache__
โย ย โย ย โโโ __init__.cpython-312.pyc
โย ย โย ย โโโ settings.cpython-312.pyc
โย ย โย ย โโโ urls.cpython-312.pyc
โย ย โย ย โโโ wsgi.cpython-312.pyc
โย ย โโโ asgi.py
โย ย โโโ settings.py
โย ย โโโ urls.py
โย ย โโโ wsgi.py
โโโ manage.py
โโโ poetry.lock
โโโ pyproject.toml
does this structure look okay?
yes (if it runs)
it does, im willing to change the most inner django_tutorial folder into src/
that should keep working and should look nice and clean right?
depends
for importable packages, there still needs to be a directory named the same as the package because of how Python imports work
but here it should be okay
since you're not making the package for external consumption
hum I see, then, maybe this should be better
manage.py and pyproject.toml might be mentioning the directory by name
.gitignore is missing (if you plan on using Git, Python almost always needs a .gitignore because of __pycache__)
im trying to figure this out
wait that one wasn't official
hmm
there is Python gitignore file somewhere
idk if Django officially provides one for project templates
Python.gitignore lines 58 to 62
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal```
ig the generic Python one is fine since it includes Django-related parts
โโโ pyproject.toml
โโโ src
โโโ manage.py
โโโ mysite
โโโ __init__.py
โโโ asgi.py
โโโ settings.py
โโโ urls.py
โโโ wsgi.py```
this looks nice and clean right?
should work
do I get this gitignore?
IDEs sometimes need to be pointed-to src directory for recognising imports
it covers most of Python usecases
@proper ridge where is call to isinstance?
@proper ridge did you reload the import?
hmm
error messages take source from file not in-memory buffer, iirc
can you restart the kernel?
@proper ridge you can't check is something is an instance of, for example, list[int], only list
!e
isinstance([], list[int])
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | isinstance([], list[int])
004 | TypeError: isinstance() argument 2 cannot be a parameterized generic
you have a []d thing inside the union
in that type alias
how is it defined, again?
you need to do isinstance(thing, Collection)
from __future__ import annotations
__all__ = ["Collection"]
from typing import (Iterator, overload, Protocol, TypeVar,
TypeAlias, Self, runtime_checkable)
T = TypeVar("T")
@runtime_checkable
class Collection(Protocol[T]):
def __len__(self) -> int:
...
def __iter__(self) -> Iterator[T]:
...
@overload
def __getitem__(self, idx: int) -> T:
...
@overload
def __getitem__(self, idx: slice) -> Self:
...
@overload
def __setitem__(self, idx: int, value: T) -> None:
...
@overload
def __setitem__(self, idx: slice, value: Self) -> None:
...
def __add__(self, other: Self) -> Self:
...
def __mul__(self, other: int) -> Self:
...
# `NestedCollection` is a type alias that represents a collection of elements
# of type T or a collection of collections of elements of type T.
NestedCollection: TypeAlias = Collection[T] | Collection["NestedCollection[T]"]
!e
isinstance([], list | set)
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
(I didn't know unions are supported)
NestedCollection[Something] also isn't entirely from how I understand how Python works
!e
print(isinstance("a"), int | float)
print(isinstance("a"), int | float | str)
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(isinstance("a"), int | float)
004 | ^^^^^^^^^^^^^^^
005 | TypeError: isinstance expected 2 arguments, got 1
-> Self on __getitem__ is wrong
it needs to return Collection[T] not Self
!e
from __future__ import annotations
__all__ = ["Collection"]
from typing import Iterator, overload, Protocol, TypeVar, TypeAlias, Self, runtime_checkable
T = TypeVar("T")
@runtime_checkable
class Collection(Protocol[T]):
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[T]: ...
@overload
def __getitem__(self, idx: int) -> T: ...
@overload
def __getitem__(self, idx: slice) -> Self: ...
@overload
def __setitem__(self, idx: int, value: T) -> None: ...
@overload
def __setitem__(self, idx: slice, value: Self) -> None: ...
def __add__(self, other: Self) -> Self: ...
def __mul__(self, other: int) -> Self: ...
NestedCollection: TypeAlias = Collection[T] | Collection["NestedCollection[T]"]
print(NestedCollection)
print(NestedCollection[int])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | typing.Union[__main__.Collection[~T], __main__.Collection[ForwardRef('NestedCollection[T]')]]
002 | typing.Union[__main__.Collection[int], __main__.Collection[ForwardRef('NestedCollection[T]')]]
^ another reason why it's wrong
!e
from __future__ import annotations
__all__ = ["Collection"]
from typing import Iterator, overload, Protocol, TypeVar, TypeAlias, Self, runtime_checkable
T = TypeVar("T")
@runtime_checkable
class Collection(Protocol[T]):
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[T]: ...
@overload
def __getitem__(self, idx: int) -> T: ...
@overload
def __getitem__(self, idx: slice) -> Self: ...
@overload
def __setitem__(self, idx: int, value: T) -> None: ...
@overload
def __setitem__(self, idx: slice, value: Self) -> None: ...
def __add__(self, other: Self) -> Self: ...
def __mul__(self, other: int) -> Self: ...
type NestedCollection[U] = Collection[U] | Collection[NestedCollection[U]]
print(NestedCollection)
print(NestedCollection[int])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | NestedCollection
002 | NestedCollection[int]
well, ce you guys, take care!
type alias syntax was added in 3.12
thought it might work
time to test
!e
from __future__ import annotations
__all__ = ["Collection"]
from typing import Iterator, overload, Protocol, TypeVar, TypeAlias, Self, runtime_checkable
T = TypeVar("T")
@runtime_checkable
class Collection(Protocol[T]):
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[T]: ...
@overload
def __getitem__(self, idx: int) -> T: ...
@overload
def __getitem__(self, idx: slice) -> Self: ...
@overload
def __setitem__(self, idx: int, value: T) -> None: ...
@overload
def __setitem__(self, idx: slice, value: Self) -> None: ...
def __add__(self, other: Self) -> Self: ...
def __mul__(self, other: int) -> Self: ...
NestedCollection: TypeAlias = Collection[T] | Collection[list[T]] # changed to list as an experiment
print(NestedCollection)
print(NestedCollection[int])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | typing.Union[__main__.Collection[~T], __main__.Collection[list[~T]]]
002 | typing.Union[__main__.Collection[int], __main__.Collection[list[int]]]
hmm
so it does propagate
Python turns out to be smarter than expected
!d typing.TypeAlias
typing.TypeAlias```
Special annotation for explicitly declaring a [type alias](https://docs.python.org/3/library/typing.html#type-aliases).
For example:
```py
from typing import TypeAlias
Factors: TypeAlias = list[int]
``` `TypeAlias` is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:
ig it takes all the TypeVars from types it has mentioned inside
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
T = TypeVar("T")
U = TypeVar("U")
Test: TypeAlias = tuple[T, U] | tuple[U, T]
print(Test)
print(Test[int, str])
print(Test[int])
:x: Your 3.12 eval job has completed with return code 1.
001 | tuple[~T, ~U] | tuple[~U, ~T]
002 | tuple[int, str] | tuple[str, int]
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 8, in <module>
005 | print(Test[int])
006 | ~~~~^^^^^
007 | TypeError: Too few arguments for tuple[~T, ~U] | tuple[~U, ~T]; actual 1, expected 2
how does it pick the order
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
U = TypeVar("U")
T = TypeVar("T")
Test: TypeAlias = tuple[T, U] | tuple[U, T]
print(Test)
print(Test[int, str])
print(Test[int])
:x: Your 3.12 eval job has completed with return code 1.
001 | tuple[~T, ~U] | tuple[~U, ~T]
002 | tuple[int, str] | tuple[str, int]
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 8, in <module>
005 | print(Test[int])
006 | ~~~~^^^^^
007 | TypeError: Too few arguments for tuple[~T, ~U] | tuple[~U, ~T]; actual 1, expected 2
order is entirely inferred from inside of the alias
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
T = TypeVar("T")
U = TypeVar("U")
Test: TypeAlias = tuple[U, T] | tuple[T, U]
print(Test)
print(Test[int, str])
print(Test[int])
:x: Your 3.12 eval job has completed with return code 1.
001 | tuple[~U, ~T] | tuple[~T, ~U]
002 | tuple[int, str] | tuple[str, int]
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 8, in <module>
005 | print(Test[int])
006 | ~~~~^^^^^
007 | TypeError: Too few arguments for tuple[~U, ~T] | tuple[~T, ~U]; actual 1, expected 2
hmm
order is still the same
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
T = TypeVar("T")
A = TypeVar("A")
Test: TypeAlias = tuple[T, A] | tuple[A, T]
print(Test)
print(Test[int, str])
print(Test[int])
:x: Your 3.12 eval job has completed with return code 1.
001 | tuple[~T, ~A] | tuple[~A, ~T]
002 | tuple[int, str] | tuple[str, int]
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 8, in <module>
005 | print(Test[int])
006 | ~~~~^^^^^
007 | TypeError: Too few arguments for tuple[~T, ~A] | tuple[~A, ~T]; actual 1, expected 2
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
T = TypeVar("T")
A = TypeVar("A")
Test: TypeAlias = tuple[T, A] | tuple[A, T]
print(Test)
print(Test[int, str])
print(Test[str, int])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | tuple[~T, ~A] | tuple[~A, ~T]
002 | tuple[int, str] | tuple[str, int]
003 | tuple[str, int] | tuple[int, str]
I have the third print for a different thing
so this one actually answers how it works
it just fills in in the order that the thing on the right has them
order does matter
!e
from __future__ import annotations
from typing import TypeVar, TypeAlias
A = TypeVar("A")
B = TypeVar("B")
C = TypeVar("C")
Test: TypeAlias = tuple[B, C] | A
print(Test[A, B, C])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
typing.Union[tuple[~A, ~B], ~C]
so type alias there can't have types partially filled in
yep.
!e
from typing import *
A = TypeVar("A")
type Partial[B] = A | B
print(Partial)
print(Partial[int])
print(Partial[int, str])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Partial
002 | Partial[int]
003 | Partial[int, str]
!e
from typing import *
A = TypeVar("A")
type Partial[B] = A | B
print(Partial)
print(Partial[int])
print(Partial[int, str, bool])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Partial
002 | Partial[int]
003 | Partial[int, str, bool]
this doesn't sound right
!e
type Partial[T] = int
print(Partial)
print(Partial[int])
print(Partial[int, str, bool])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Partial
002 | Partial[int]
003 | Partial[int, str, bool]
this is not right at all
!e
type Partial[T] = bool
print(isinstance(0, Partial[int]))
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(isinstance(0, Partial[int]))
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: isinstance() argument 2 cannot be a parameterized generic
!e
type Partial[T] = bool
print(isinstance(0, Partial))
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(isinstance(0, Partial))
004 | ^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
okay so it's just not a type
and Python has no clue what type aliases actually resovle to
I need an actual language server to test this
Pyright/Pylance
type statements are just for type aliases
they are quite different
You can give an alias type parameters, but any type parameters on the RHS have the be on the LHS
for LSPs they might be same, but for the language they're different
I broke Pylance I think
this type alias makes no sense but Pylance doesn't catch it
it just goes "this is not generic"
this is perfectly fine:
It's a recursive type alias
Like imagine you needed to create a type alias for "things that can be converted to JSON" ```py
type JSONable = bool | None | int | float | str | list[JSONable] | dict[str, JSONable]
Oh right
I'm actually not sure I understand the semantics of this
But yeah you can add whatever type parameters you want on the left hand side. This was syntax added in 3.12 I think?
only allows stuff like [[[[]]], [[[], []]]]
I think
hmm
@proper ridge Are you familiar with the new syntax for adding type parameters to functions and classes? E.g. ```py
def foo[T](xs: list[T]) -> T:
return xs[0]
Right, I'll find the relevant docs...
It's a way of constraining the relationship between the different types of the function signature.
this is basically list[list[list[...]]]
that includes [[], [[]]]
Oh. That's just syntax that was added in python 3.12
[T] on function is just a different way to define TypeVar
It's equivalent (roughly) to what AF wrote
it should be equivalent type-wise because T is invariant
It's a bit of syntactic sugar mostly.
more correct:
T = TypeVar("T", infer_variance=True)
def foo(xs: list[T]) -> T:
return xs[0]
This is a longer document about it: https://peps.python.org/pep-0695/
With rational etc.
!e
def foo[T](xs: list[T]) -> T:
print(T)
foo([])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
T
!e
def foo[T](xs: list[T]):
print(T)
foo([])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
T
Covariant, invariant, and contravariant have a technical meaning when talking about type parameters @proper ridge
There's a nice explaination in one of the PEPs
Or I could explain it if you like? ๐
Actually, this might be a good explaination: https://realpython.com/python-type-checking/#covariant-contravariant-and-invariant
Essentially, a generic type G[T] is covariant with respect to its type parameter T if: A being a subtype of B implies thatG[A] is a subtype of G[B].
this is closer to reality
def contravariant[T](x: T): ...
def covariant[T]() -> T: ...
def invariant[T](x: T) -> T: ...
def what[T](): ...
if those are methods on SomeType[T]
(self omitted)
Sequence[T] is covariant over T
MutableSequence[T] is invariant over T
So like, in python, bool is a subtype of int, so the type tuple[bool, ...] is a subtype of tuple[int, ...], because tuple is covariant. I.e. you can pass the former wherever the latter is expected.
Callable[[T], None] is contravariant over T
Sequence[bool] is Sequence[int]
Callable[[int], None] is Callable[[bool], None]
yes, contravariance flips subtyping
or, merged together:
Callable[[int], bool] is Callable[[bool], int]
exclusively owned list is covariant
list is not covariant because it's mutable. You can't in general pass a list[A] where a list[B] is expected, even if A is a subtype of B, because you can mutate list[B] in ways that you wouldn't be able to do to list[A] (i.e. you can append a B to a list of B but not to a list of A)
which Python can't guaranteee
Yeah I think that's what you just said/read actually ๐
Not quite
Contravariant means if A is a subtype of B, then G[B] is a subtype of G[A].
This I think is only mostly the case when dealing with higher order functions.
class Contravariant[T]:
def push(self, item: T): ...
x: Contravariant[int] = ...
x.push(1)
x.push(True)
y: Contravariant[bool] = x
y.push(True)
Like, imagine a function expects be be given another function that operates on BsAs. You could instead pass it a function that operates on AsBs.
unlike Python, in Rust Vec<T> and &Vec<T> are covariant over T but, like Python, &mut Vec<T> is invariant over T
Sorry, wait, I think I've got that mixed up 
Let me make an example instead.
class Contravariant[T]:
def push(self, item: T): ...
def test_int(contra: Contravariant[int]):
x.push(1)
def test_bool(contra: Contravariant[bool]):
x.push(True)
x: Contravariant[int] = ...
test_int(x)
test_bool(x)
you can .push bools because they're ints
if it can accept int, it can accept bool
therefore all things that accept ints can accept bools
whereas something that only accepts bools can't accept ints
all bools are ints in Python
def silly_function(
fn: Callable[[bool], Any],
x: bool,
) -> Any:
return fn[x]
def negate(x: bool) -> bool:
return not x
def addone(x: int) -> int:
return x + 1
silly_function(negate, true)
silly_function(addone, true)
2 can't be interpreted as bool
this is the issue
Callable is contravariant w.r.t. the types of the arguments (I think).
yes
I.e. it's ok to pass a Callable[[int], Any] where a Callable[[bool], Any] is expected.
Because whatever you can do with the latter you can do with the former.
It's contravariant.
Imagine I'm a function
The contract I have with the caller of the function is that they will pass a function fn that I can apply to bools
If they pass me a function I can apply to ints, I'm fine with that, because bools are ints
Nah, because say, as the function, I try to do fn(123).
I couldn't do that if fn is Callable[[bool], Any]
Because 123 is not a bool
does new generic syntax allow specifying variance? (I think I remember seeing it somewhere)
I don't think so, I think it's inferred
If I'm a function, and I'm being passed a function, all I care about is "what can I do with this function?". I don't mind if the function I was given accepts a broader range of arguments than I intend to give it. @proper ridge
useful table
https://peps.python.org/pep-0695/#summary
If that makes sense ๐
a bit incorrect about Rust: it does have variance and it is inferred
Because Callable[[int], Any] can be used wherever Callable[[bool], Any] can be used. The former accepts the same set of argument values as the latter (and more!)
why is so much programming related to toilet jargon? passing args, streams, flushing, code smell ..
I mean it can be passed whatever argument the latter can be.
So if I asked for a Callable[[bool], Any] and instead I'm given a Callable[[int], Any], I don't mind. I got more than I bargained for.
Sorry, I tend to understand better by giving personalities to things ๐
In git, the front end is called porcelain and the backend is called plumbing. Which maybe is some kind of statement about the quality of the code passing through that system.
Oh yeah
Erm yeah so contravariant means: A < B implies G[B] < G[A], where < means "is a subtype of".
Covariant means: A < B implies G[A] < G[B]
And invariant means nothing is guaranteed.
The mutability is the weird part. Like when I learned that list is invariant it surprised me, but it makes sense if you think about it and look at a few examples.
i'm going to start using that in my work... "all analysis based on data in this report is invariant"
@worn canopy Can't really hear you
Sounds like a bad microphone connection
Ah
๐
Gotta go ๐ Back in a bit
is this a decent download sped?
yes, anything >100mbps is relatively good network-wise; and around 200~600 mbps is where it starts hitting CPU and HDD limits, from what I've seen
I'll try to be back on later. Got a whole crap ton of things dropped on me
it kinda
sucks that I need
to wait 3d and send
50 msgs to be abe
to talk on vc
44 msgs to go ig
sup
ur employer said this mf goin on vacay let's get all of the year's work from him today
you'll play only one
hell divers
workaholic
@misty sinew Yo
use wired conn like a real IT person
every IT guy knows wired > wifi
your fault for buying featureless laptops
Heyy
Working late again?
Ah right nice
Yeah, trying to force yourself to sleep never works ๐
ยฏ_(ใ)_/ยฏ
Ah yes, brick ๐งฑ
Errm, I've spoken like once here I think
I'm a bit microphone shy ๐
plome?
Ohh
Right yeah
Like a self-describing word
But I can't remember the word for that
Oh I was thinking "autological"
Nominative determinism
Anyone used streamlit before
urban dictionary
Word of the day on Wiktionary is "bisexual lighting" 
trace this
The online etymology dictionary (etymonline) is the internet's go-to source for quick and reliable accounts of the origin and history of English words, phrases, and idioms. It is professional enough to satisfy academic standards, but accessible enough to be used by anyone.
pretty sure lighting doesn't have a sexual orientation attr
It's similar to "mexican lighting" from breaking bad

but for bisexual purposes
Showered in golden light
In photography, the golden hour is the period of daytime shortly after sunrise or before sunset, during which daylight is redder and softer than when the sun is higher in the sky.
The golden hour is also sometimes called the "magic hour," especially by cinematographers and photographers. During these times, the brightness of the sky matches the ...
Very nice
A beautiful effect, not dreary, IMO
Yea, birthdays stop mattering after a while
the first few decades are fun
I just listen to this song
Boo @ the failed embed
it was blocked by the uploader for reasons
so I removed it
play it
Yeah
Mhm
Oh yeah, I think capitalisation differs between languages
I know in Italian they would say 'inglese' not 'Inglese' for example
@hoary tide ^^^
Many words that are capitalized in English are not capitalized in Italian. These include: the days of the week, the months of the year, proper adjectives, a few proper nouns, and titles such as Mr., Mrs., and Miss.
Happy Holidays!
umm....
so I can help with that a little...
and yes its pytorch
let me go find the website... it hugging something...
Ty
He plays a robot though
ya its the best one
Nah, James Cameron
What is S-mode?
There is a lightweight version!?
I want that on my phone lol
for reading emails.
^only for reading emails specifically
same
it's friday + 1
friday++
Sounds similar to the post office scandal here
sleep tight peep's
Cya ๐
++friday is faster
Lovely singing hemlock ๐
Apparently he's doing better with undecided voters after the debate ๐คทโโ๏ธ
No I mean Biden is doing better sorry
let's make a bot to influence the elections 
Oh ok so a different news source says the opposite lol
Yeah
what is polling
via sampling?
just take a biased sample
produce false prediction.. influence outcome
They do... but its unsupported. Youc an request it for testing purpose for windows
Neat, I legit wasn't aware
Genocide Prevention and the Responsibility to Protect
I think there are many awesome resources of lists out there... but generally with AI it really depends on what your application. What hugging face is a example list of AI models that easier to search than GitHub. Developed and maintained by AI researchers so they can have heated AI discussions. Lets talk about popular AI to understand why why this is a useful link:
https://huggingface.co/
Rambling explanation about AIs (part 1 of 2):
- Pytorch is best because its a broad for complex AI that are based on video and unstructured data. True AI and mostly under this umbrella because pytorch supports non-python AI models.
- Google's Tensorflow and Google's Vertix-AI: Tensorflow 2 is generally for text mining and text unstructured data, photo image recognition models, and very unclean structured datasets. The problem with tensorflow is most of the awesome stuff was in tensorflow 1. With tensorflow 2, they added BERT, but stripped out most of the controls for trying to "understand your AI" (Don't get me on Google Rant). Now Vertix-AI is Google quick platform to beat Chat-GPT and is """Tensorflow version 3 devOps IDE"""
- Chat-GPT and Microsoft's AI: Let's not kid ourselves--Microsoft owns Chat-GPT. Chat-GPT trained on all of Microsoft's data. Azure ML Studio and Azure's pythonsdk are that """devOps IDE""" of Microsoft AI called Co-pilot.
- Facebook's AI: Facebook's prophet has the best for forecasting of any AI model (with only the R-package called modeltime beating it on tests of predicting bitcoin prices). Facebook has an new AI similar to CHAT-GPT called LLaMa2.
Rambling explantion about AIs (part 2 of 2): Overwhelmed? Good. Those are just the popular AIs that for all the same problems sets. On ResearchGate... there are over 1000+ organizations with at least 5 AI models all actively doing AI . (THE POINT) .... AI has a huge problem ... Across any industry not only are the packages not standardized anymore both the IDE developing platform is not standard.
Huggingface (like paper's with code) is the solution to that problem. Its a way of sharing the models and standardizing results. So its great as a starting point for AI applications.
I would like to work a small ChatGdt Ai by using python
to do?
Ya and my uncle planing for it but he told me u need a good tool for that lol
If its making an AI to talk with there is a better website... than ChatGPT.... the fanfition discords kind of went crazy with ChatGPT.
I can make an app for it
Lol
where do youi the Gamer US presidents came from lol... fanfiction. Alot of fanfiction writers.
Hm?
wydm xd
Google US presdient play gatch games.
https://character.ai/chat/7Nlj1NdBqpt4zMC5nq-aHr9MTe9kIwJEt0EtRPWfYvM dont' ask it python question its not accurate.
Meet AIs that feel alive. Chat with anyone, anywhere, anytime. Experience the power of super-intelligent chat bots that hear you, understand you, and remember you.

yep now if you look on fanfiction . net for Guido van Rossum you will find there are tons of fanfics where he is like the Bill Gates cameo appearance.
so seriously find out what you uncle wants to do with AI.
in the mean time here: https://huggingface.co/spaces?sort=trending&search=chatgpt
@mild flume Have a nice weekend dude ๐
What is space
Grenade is a non-food thing that can effect your brain :3
the federation is cool
I like how ur flag it doesn't exist
you can view it through the mobile ui
the default desktop client doesn't allow it
Nope i cant even see it
or something
xd
Are you using the discord mobile app?
more python less debate plz
But what about where did Walter white go
Python fun
Using R is better
Time to make heat map
Of a csv data set
Sorry thats anaconda
Are you still fostering
Holy thats giant
The Canon โMagic Drainpipeโ, the name alone conjures up something of legendary status. I often dreamt of acquiring this lens as a younger photographer, but it never made its way into my collection. To me, the โmagicโ lens had so much more intrigue than the white plastic 70-200mm zoom lenses I saw us
Hobby or profession
?
hobby
Thats cool
millennial
a person born between the early 1980s and the late 1990s; a member of Generation Y.
very few people here
making websites and ui ux
@sly pond do you android studio
or xcode
@sly pond when did you start?
how big was your portfolio @sly pond
before starting
very true
data science for resumes ๐ค @sly pond
lol
i just want 60k ngl
awe
I just want a zillion billion dollars๐ญ
blease give
lol i just want apartment
and a cat min
just something i could say i could die happy
id like to build a datacenter in the midle of nowhere be a better person give all my money away
die with nothing
sounds nice
have money but eh
fair
just a work from home
a nice view
and coffee is the dream
work on data
even grunt work id be happy
awe so cissp
what you do
just apartment food and cat
hi could anynoe help me with a keysystem im trying to get to work?
key system whats that
simply said a system where i generate and store keys
i just got 2 issues
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
me toi
@sly pond thats the dream
the poblem witht the genkey func is that whenever a key is generated the epxiry is already set which is wrong. the expiry should be set when redeemed becaus it would just take the generated date and use that to expire wihtout being redeemed
view and coffee
im sorry its kind of a complex system
So how does the scoring work in olympic breakdancing? ๐
{
"test-aEZnWpDsh5CsDATNE9Ya-R0HMfc2kotvDc0Y86KE6": {
"days": 1,
"generated_date": "2024-06-29 03:00:33",
"expiry": "2024-06-30 03:00:33",
"used": false
}
}```
the issue here is that i gen a key today and the expiry is already set
what it really is like i make keys for my customers to redeem to be able to use my bot
i store them
with necessary info
how for how long?
not for a set period of time
its for any time
for example i run /genkey 1 1 which would give me 1 key for 1 day expiration. the issue now is that "expiry": "2024-06-30 03:00:33", is already set since i today gened a key but that causes an issue since the key should only expire after being redeemed
udnerstand ๐ญ
oh so you want a validation between the account and the key
kinda
lemme upload my complete file
might make things more clear
send me the screen shotty
thats actually epic
breakdancing in the omlypics
that show is funny @sly pond
Weโre always with you, Mac. Watch this selected scene from the season 13 finale of Sunny.
Subscribe now for more Itโs Always Sunny In Philadelphia clips: http://bit.ly/SubscribeFX
The gang returns, mostly, in the next season of FXXโs comedy series Itโs Always Sunny in Philadelphia. The gang has its hands full as Charlie hopes to have a child...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
thats it
i enjoy their gay humor
it is
its a great way to express yourself
LMAO this is my first time seeing this
issue is.
i make key with the expiration of 1 day but when i generate it the expiration is set alerady. thats wrong becuase the key should only expire after being redeemed
@sly pond you sound a lot like steven west from the podcast philosophize this
Listen to this episode from Philosophize This! on Spotify. Today we talk about some of the benefits of being a practitioner of philosophy. Michael Sandel's view of the three main approaches to justice throughout the history of philosophy. The strengths and weaknesses of all three. The consequences of replacing social norms with market norms. And...
@sly pond
okay almost
but i think he sounds like steven west
then again steven is a bit older
i will listen to his podcast now
bye everyone have a nice afternoon
perhaps night
lol
Oh shid
I came in here to listen to something to snooze
Keep talking about programming
Stop drinking before you get cirrhosis
Boi what
Rehab time
You sound like you use collab
Ok letโs revisit this convo when ur 19
Just donโt get shitfaced
Youโll be alright
LMao
You do the crime you do the time
"there are women and children down there, they're all unarmed"
"Gotcha, proceed eliminating them" this is gold๐ญ
love it
I want to make some projects for Web development trough django in python.
So, I will use VS. Code . Again, Someone please give me the idea of installing Django fisrt in the VS.Code terminal , then virtual machine, then MS-SQL (If Needed). And any project name-For Example.
hi
Let's see. Firts, get Poetry using pipx.
Create your folder.
poetry init```
Do not install any dependencie.
```py
poetry add Django
poetry run django-admin startproject my_site
Now you should have something like:
โโโ my_site
โย ย โโโ manage.py
โย ย โโโ my_site
โย ย โโโ init.py
โย ย โโโ asgi.py
โย ย โโโ settings.py
โย ย โโโ urls.py
โย ย โโโ wsgi.py
โโโ poetry.lock
โโโ pyproject.toml
The outer "my_site" folder, you can rename it like you want, in my case its "src", and the inner my_site its the actual name of your project.
I'm a SixthGen Italian and i dry my ass in the sink
My name is Jack Jaconelli, and i drink F Scotch
hi hows all
helo
backend haven ?
/// py
/// py like this
def try_func():
return
yeah ``` from pyresparser import ResumeParser
def extract_skills_with_pyresparser(file_path):
data = ResumeParser(file_path).get_extracted_data()
return data.get('skills', [])
Example usage
file_path = './resume/CV.pdf'
skills = extract_skills_with_pyresparser(file_path)
print(skills)``` py
from pyresparser import ResumeParser
def extract_skills_with_pyresparser(file_path):
data = ResumeParser(file_path).get_extracted_data()
return data.get('skills', [])
# Example usage
file_path = './resume/CV.pdf'
skills = extract_skills_with_pyresparser(file_path)
print(skills)
did you see the error ?
i don't even have config.vfg that's the problem
cfg
i did not understand you im sorry
yeah
and how could i use them
yeah
if i return the data you mean ?
same error
do i have to create a config.cfg or what
i don't know what should be in the file actually
spaCy
python -m spacy download en_core_web_sm
nltk
python -m nltk.downloader words
python -m nltk.downloader stopwords
yeah
no worries
it's like i used spacy in my other project but i had to specify every pattern for name and email and the skills
i wanted to use pyresparser becuase this liabrary extract them automatically without me specifying what should i extract or specify the patterns
okay i donwloaded them and then i try to execute or there is something i should a dd in the code
from pyresparser import ResumeParser
data = ResumeParser('/path/to/resume/file').get_extracted_data()
okay wait
mm i gues i have to create a new file called cofig.cfg
i had the same error
okay
yo @obtuse valve
yo
@devout fern #voice-verification
oooh
Yep
Hello
I think it has like a chocolate lining to stop it going soggy? ๐ค
Hey @proper ridge do you still need help with that Docker thing?
@proper ridge Could you link to the Github issue?
Because it's from an Islamic country?
Sorry, I'm not sure I understand.
Right ๐ค
Rosewater?
yes
@viscid shore Sorry for the wrong ping.
@proper ridge I'm right here.
You said you were looking for the legend.
DO IT TO JULIA!
@tall hound @craggy jetty @misty sinew @main drift ๐
@spice scroll ๐
@polar heron ๐
@split epoch ๐
@leaden otter Can you hear me?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
it wont run
import datetime
def get_next_day(year, month, day):
input_date = datetime.date(year, month, day)
next_day = input_date + datetime.timedelta(days=1)
return next_day
def main():
print("Enter the date:")
year = int(input("Year: "))
month = int(input("Month: "))
day = int(input("Day: "))
try:
next_day = get_next_day(year, month, day)
print(f"The next day is: {next_day}")
except ValueError as e:
print(f"Error: {e}. Please enter a valid date.")
if name == "main":
main()
yes it seems correct
but when i run this file terminal says there is error
import datetime
def get_next_day(year, month, day):
input_date = datetime.date(year, month, day)
next_day = input_date + datetime.timedelta(days=1)
return next_day
def __main__():
print("Enter the date:")
year = int(input("Year: "))
month = int(input("Month: "))
day = int(input("Day: "))
try:
next_day = get_next_day(year, month, day)
print(f"The next day is: {next_day}")
except ValueError as e:
print(f"Error: {e}. Please enter a valid date.")
if __name__ == "__main__":
__main__()
You need to add __ to main.
ok it worked
but what was the problem in my code
AttributeError: module 'datetime' has no attribute 'date'
now i have this error
!d datetime.datetime.date
datetime.date()```
Return [`date`](https://docs.python.org/3/library/datetime.html#datetime.date) object with same year, month and day.
!e py import datetime print(datetime.datetime.date)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
<method 'date' of 'datetime.datetime' objects>
!e py from datetime import datetime print(datetime.date)
yes
:white_check_mark: Your 3.12 eval job has completed with return code 0.
<method 'date' of 'datetime.datetime' objects>
!e ```py
def main():
print('Hello, world.')
if name == 'main':
main()```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world.
no there is a run python file button
Open terminal.
ok
[Errno 2] No such file or directory
Where is your file?
You haven't opened your folder here.
Right click on your file and send me the path of it.
C:\Users\alium\Desktop\รdev\datetime.py
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Send me the error please.
@vagrant hill ๐
Traceback (most recent call last):
File "C:\Users\alium\Desktop\รdev\datetime.py", line 21, in <module>
main()
File "C:\Users\alium\Desktop\รdev\datetime.py", line 15, in main
next_day = get_next_day(year, month, day)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\alium\Desktop\รdev\datetime.py", line 4, in get_next_day
input_date = datetime.date(year, month, day)
^^^^^^^^^^^^^
AttributeError: module 'datetime' has no attribute 'date
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
Type this in your terminal.
py -3 --version
Python 3.12.4
@sharp thunder ๐
Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)] on win32
import daytime as daytime
I can't open my microphone
You need to complete the voice verification.
yes
but still invalid syntax
i changed the name
sakd
.py
random clciks on keyboard
python C:\Users\alium\Desktopรdev\sakd.py
Change it to datetime.
import datetime
def get_next_day(year, month, day):
input_date = datetime.date(year, month, day)
next_day = input_date + datetime.timedelta(days=1)
return next_day
def main():
print("Enter the date:")
year = int(input("Year: "))
month = int(input("Month: "))
day = int(input("Day: "))
try:
next_day = get_next_day(year, month, day)
print(f"The next day is: {next_day}")
except ValueError as e:
print(f"Error: {e}. Please enter a valid date.")
if name == "main":
main()
yes
yes
u are my saviour
thanks
it worked
but can you explain what was the problem to talk like a 5 year old
nok
nope
can you explain to me like im a 5 year old
im new to this
oh
i get it
thanks for everything
have a good day
My pleasure
yeah looks like I have to spam messages 50X
haha Im kidding
today imma code up a caching system for my mcts code
rizzle diesel
@misty sinew ๐
gobblestone
did you make the original class?
class Service:
def __init__(self,
api: str,
device: str="CPU") -> None:
if api != "api":
raise ValueError("API invalid.")
self.api = api
self.device = device
def run(self, circuit: str) -> dict:
return {"result": circuit}
have a shared interface that both original and mock implement
you can even formalise it
there's more than one method to do mocking for tests
are you using the thing that the library provides?
Yeah, I'm using unittest.mock.
(I don't like those because they're not type-correct, and so in more strict languages they don't work)
I prefer not having objects be so complex that the only way is to monkeypatch/mock them
kay guys, gotta got
Byeee
one of type-strict ways to do this is:
class Interface(abc.ABC):
@abc.abstractmethod
def example(self): ...
class Implementation(Interface):
def example(self): ...
class MockImplementation(Interface):
def example(self): ...
depends on how complex the behaviour is
if I understand correctly, unittest.mock does allow choosing outputs depending on inputs
!e
from unittest.mock import Mock
mock = Mock(side_effect=KeyError('unknown input'))
values = {'a': 1, 'b': 2, 'c': 3}
mock.side_effect = values.__getitem__
print(mock('b'))
print(mock('c'))
print(mock('a'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2
002 | 3
003 | 1
