#internals-and-peps

1 messages Β· Page 70 of 1

feral bane
#

i guess you could make it so the keyword is only allowed in funtions

#

might be slightl confusing

grave jolt
#

and if it's inside a function, it's hopefully easy to see than a variable is not mutated πŸ™‚

gleaming rover
#

and if it's inside a function, it's hopefully easy to see than a variable is not mutated πŸ™‚
@grave jolt yeah, that's what I was thinking

#

because IIRC Final doesn't work for local variables?

#

and it would be nice to have something that a 3rd-party checker could pick up

feral bane
#

inside a function could allow more optimizations too

gleaming rover
#

inside a function could allow more optimizations too
@feral bane it could, but it would also be significantly more work for the core team, I guess

raven ridge
#

I mean like:

const x = 1
x = 2  # SyntaxError

@gleaming rover how's it interact with nonlocal? With globals()? With exec?

#

With rebinding from another module? What if there was:
a.py:

const x = 0

b.py:

import a
a.x = 10
feral bane
#

nonlocal shouldn't be a problem

#

lookup for nonlocal isn't dynamic, it knows when it's compiled what function the variable is from

#

i do think it's untenable to try to do this for scopes that aren't functions

#

though you could conceivably make a descriptor that does it for instance variables

feral bane
#
class InitOnlyVar:
    def __init__(self):
        self.default = default
    def __get__(self, obj, objtype=None):
        return obj.__dict__[self.name]
    def __set__(self, obj, val):
        if self.name in obj.__dict__:
            raise AttributeError("readonly attribute")
        obj.__dict__[self.name] = val
    def __set_name__(self):
        self.name = value

class InitOnlySlotVar:
    def __init__(self, name, descriptor):
        self.descriptor = descriptor
        self.name = name
    def __get__(self, obj, objtype=None):
        return self.descriptor.__get__(self, obj, objtype)
    def __set__(self, obj, val):
        try:
            self.descriptor.__get__(self, obj)
        except AttributeError: #good
            self.descriptor.__set__(obj, val)
        else:
            raise AttributeError("readonly attribute")

def setup_initonly_slots(cls):
    # called after class definition
    slots = cls.__initonly_slots__
    if isinstance(slots, str): slots = (slots,)
    for name in slots:
        desc = InitOnlySlotVar(name, getattr(cls, name))
        setattr(cls, name, desc)
#

to use the regular one just use varname = InitOnlyVar(), and it creates a descriptor that can only be assigned once,

#

to use the slot one, define __slots__ as normal, __initonly_slots__ as the ones you want to have this behavior, and then call setup_initonly_slots(Class) after the class is defined

gleaming rover
#

@gleaming rover how's it interact with nonlocal? With globals()? With exec?
@raven ridge you mean at runtime?

#

honestly I forgot about Final

teal yacht
#

with how breakable python is, having static analysis tools send a nice f-u message to people abusing its """"features"""", or straight up pretending they don't exist is the best we can do

pseudo cradle
#

Sometimes I wonder what dynamic typing really brings to the language

#

I can't really think of anything

#

Other than saving you time from typing things out

gleaming rover
#

Other than saving you time from typing things out
@pseudo cradle type inference helps with that

teal yacht
#

because there isn't anything, programs generally aren't even designed in a way that takes advantage of dynamic typing

feral cedar
#

it looks nice

gleaming rover
#

I'd say the main advantage of dynamic typing is letting you write programs that "almost work" quickly

teal yacht
#

i guess if people are fine with that shrug

pseudo cradle
#

It's also the main disadvantage, tbh

gleaming rover
#

i guess if people are fine with that :shrug:
@teal yacht throwaway scripts + small programs I guess

teal yacht
#

i think "almost working" is worse than "never working" in a crushing majority of case tho

pseudo cradle
#

Like, even if you just really really need dynamic typing that's what unions are for?

gleaming rover
#

Like, even if you just really really need dynamic typing that's what unions are for?
@pseudo cradle that's not what unions are for IMO

#

you mean like sum types?

pseudo cradle
#

Like, if you're trying to declare the return type of a function and you don't know if it's going to be a list or a bool

gleaming rover
#

uh...

#

that seems somehow orthogonal

pseudo cradle
#

(Was an example I saw on SO)

teal yacht
#

i just wish global type inference was standard and we'd just never write types anymore

#

i swear python code has more types written than f#

gleaming rover
#

i just wish global type inference was standard and we'd just never write types anymore
@teal yacht isn't it undecidable in the general case

teal yacht
#

depends on the type system, but yeah in common oop-like type systems, it's not decidable

raven ridge
#

@raven ridge you mean at runtime?
@gleaming rover yeah.

gleaming rover
#

@gleaming rover yeah.
@raven ridge I was thinking a compile-time check, and then, yes, I remembered Final

#

although on that topic the equivalent of descriptors for modules would be nice too

raven ridge
#

my point is that a compile time check isn't sufficient - Python is such a dynamic language that there's no way a compile-time check will do the trick.

#

it can't possibly prevent something like:

def func(stmt):
    const x = 0
    eval(stmt)
    print(x)
func("x = 5")```
gleaming rover
#

no

#

I was envisioning something like type hints

#

i.e. no runtime enforcement by design

#

which is why I mentioned Final

raven ridge
#

ah. 🀷

#

I mean, it'd give linting one extra mistake it could catch. But if we're talking about language changes that would make linting more effective, I don't think that's the most effective one...

gleaming rover
#

I mean, it'd give linting one extra mistake it could catch. But if we're talking about language changes that would make linting more effective, I don't think that's the most effective one...
@raven ridge probably not? but it's something that's personally relevant to me because I more or less never reassign

raven ridge
#

some of the suggestions above would basically just be a different language. "Python, except with static typing", even with perfect type inference, would just be an entirely different language than Python.

gleaming rover
#

some of the suggestions above would basically just be a different language. "Python, except with static typing", even with perfect type inference, would just be an entirely different language than Python.
@raven ridge did anyone suggest Python but statically typed?

raven ridge
#

Sometimes I wonder what dynamic typing really brings to the language
@pseudo cradle I mean, pretty much πŸ˜„

gleaming rover
#

fair enough

teal yacht
#

mypy with --disallow-untyped-functions would be statically typed python

pseudo cradle
#

I'm going through and type hinting everything anyway

raven ridge
#

mypy is... not good.

pseudo cradle
#

Or at least making a half-hearted attempt to and giving up

raven ridge
#

I literally can't use mypy in a medium sized project without finding a bug, or limitation, that makes me need to go through ridiculous contrivances to work around it.

gleaming rover
#

I literally can't use mypy in a medium sized project without finding a bug, or limitation, that makes me need to go through ridiculous contrivances to work around it.
@raven ridge indeed.

teal yacht
#

i wouldn't call it good either, but it's orders of magnitude better than nothing imo

gleaming rover
#

also having to use untyped libraries is just 😦

raven ridge
#

and there are common Python idioms that mypy just throws up it's hands about.

teal yacht
#

honestly i find it unusable atm because nobody uses it, it's a terrible vicious circle

raven ridge
#
_NOT_SET = object()
def some_func(param=_NOT_SET):
   ...

Try typing this. Whoops.

#

I actually do use mypy.

#

my team had a vote, I lost πŸ˜„

teal yacht
#

i don't think every python code is worth existing tbh

raven ridge
#

I don't like it, and find it ridiculously frustrating. More than once I've had to rewrite code to get it into a different form that mypy could adequately describe, heh

teal yacht
#

type systems by their very definition make some programs invalid

raven ridge
#

i don't think every python code is worth existing tbh
@teal yacht fair enough, but that was a common Python idiom for a very long time.

#

there is tons of existing code, part of public interfaces, that cannot be described by mypy. That's not ideal.

safe hedge
#

I just find typehints get unwieldy very fast when dealing with highly variable data

#

Unless you just say fuck it and pass Any half the time

teal yacht
#

the goal is to find a way to express logic through the type system, minimizing the amount of buggy program that gets validated, while maximizing the amount of program that does get validated

safe hedge
#

Because constructing the actual type hint for the allowed types gets really long and convoluted

teal yacht
#

look up protocols

#

and learn about the standard abstract classes

#

these are so underused it makes me sad

raven ridge
#

the goal is to find a way to express logic through the type system, minimizing the amount of buggy program that gets validated, while maximizing the amount of program that does get validated
@teal yacht if you're writing brand new code, perhaps. But when you're trying to add annotations to existing code (that was idiomatic before mypy existed!) it's nothing but disappointment.

teal yacht
#

especially in a language like python, structural subtyping is a blessing

#

it's just so uncommon in programming in general that it's hard to make it take off

raven ridge
#

the structural subtyping stuff in mypy actually is pretty cool. πŸ™‚

safe hedge
#

Like this is grim imo: Dict[Union[str, int], Dict[Union[str, int], Union[str, int, None, Dict[Union[str, int], str]]]

raven ridge
#

Sphinx now reads type hints and uses it to infer types for parameters. It almost works.

#

I have an API that I haven't yet figured out any meaningful way to type, actually. I've just thrown up my hands and given up on it.

#

I've got a DB-API 2.0 compliant database API that allows the user to set a row_factory property on a Connection to control the type of result rows. So you can do conn.row_factory = namedtuple_row_factory to get rows as namedtuple instances, or conn.row_factory = dict_row_factory to get rows as keys, etc.

#

so the method that fetches a row from the database returns - well, any type of object at all. It's a type of object that the user configured in advance, but there's no way to describe that to mypy

safe hedge
#

That's just Any no?

raven ridge
#

I mean, maybe, but then the user is forced to cast to a type they've already configured.

safe hedge
#

I mean really what you've got there is a limitation of static-type checking when you have a dynamic type

#

If you are allowing the user to dynamically define the return type how can you possibly expect mypy to check that

raven ridge
#
conn.row_factory = dict_row_factory
for row in conn:
    print(row.keys())

Typing that as Any won't make mypy happy. Typing it as Dict is a lie in the general case. The user needs to do something ridiculous like:

conn.row_factory = dict_row_factory
for row in cast(Dict[str, Any], conn.execute(statement)):
    ...
#

If you are allowing the user to dynamically define the return type how can you possibly expect mypy to check that
@safe hedge I mean, I agree, but I've got users that are all like "why doesn't this library have type hints blah blah blah"

gleaming rover
#

I mean really what you've got there is a limitation of static-type checking when you have a dynamic type
@safe hedge I'm pretty sure there's a way to type this in a sufficiently powerful static type system

raven ridge
#

and the answer is that, given the constraints of mypy, it cannot.

gleaming rover
#

because each factory knows its own type

safe hedge
#

But isn't the user providing the factory?

#

Not just picking from a few available ones?

gleaming rover
#

as long as the factory is typed, it shouldn't matter

#

like I'm not saying that mypy can do it

#

but the equivalent pattern in a statically typed language should be doable

raven ridge
#

Not just picking from a few available ones?
@safe hedge technically, yes, though the library provides several, and in practice I've never seen anyone provide one that didn't come from the library.

safe hedge
#

How much of statically typed language do you want to incorporate before you just say fuck it and make python fully statically typed

#

At some point you accept the trade-offs no?

raven ridge
#

I mean, I don't have a problem with dynamic typing. I find mypy annoying πŸ™‚

safe hedge
#

I use typehints in my own code but mainly so I remember how I intended to use the functions tbh

#

I don't even use a static type checker

gleaming rover
#

I don't even use a static type checker
@safe hedge do PyCharm's checks count

safe hedge
#

Well I use an editor not an ide..

raven ridge
#

I generally don't write application code, I generally write library code. So, users ask for type hints because they want to type their applications, and - well, sometimes I can provide them,, I guess.

safe hedge
#

I guess that's fair

#

But tbh I think good documentation is fine

raven ridge
#

not when they want to mypy --strict their code.

safe hedge
#

Yeah but that's on them

#

Sometimes I'm so glad the majority of code I write I am also the user

raven ridge
feral cedar
#

huh

safe hedge
#

@raven ridge Hmm, that's basically like DictCursor from pymysql right?

#

Does that have typehints?

raven ridge
#

don't know pymysql, but that sounds like it's probably similar.

low lagoon
#

@fast hamlet this isn't relevant to anything here.

safe hedge
#

psycopg2 has one too

#

Hmm psycopg2 doesn't have typehints

raven ridge
#

yep. The idea of making the row type configurable is pretty common across DB-API interfaces.

safe hedge
#

Unless you're pyodbc which just leaves it up to you

raven ridge
#

and I expect none of them have figured out any way to type this, because as far as I've been able to tell mypy is insufficiently expressive to handle it. πŸ™‚

safe hedge
#

Although I presume that in reality all implementations are just wrappers around the standard return type of a list

#

Like the pyodbc recommended method to get dicts is:

raven ridge
#

in some sense - the database returns one particular type of thing, at the level of the wire protocol, and then the DB-API interface is responsible for massaging that into Python types for the user to consume.

safe hedge
#
columns = [c[0] for c in cursor.description]
res = [dict(zip(columns, r)) for r in cursor]
safe hedge
raven ridge
#

yep, very true. The spec only requires a tuplesequence of column values.

safe hedge
#

I think psycopg2 is my favourite python db api

#

I'm always frustrated using others that don't seem as well featured

raven ridge
#

I haven't used it. Any particular extensions that stand out?

safe hedge
#

psycopg2.sql is really useful for constructing arbitrary statements with escaped values

#

Effectively allows you to safely parameterise table names for example

#

I think it handles bulk inserts reasonably well too

radiant fulcrum
#

It doesn't do much to any filtering of formatting

#

It only does very very basic escapes for table names because at the end of the day it's still string formatting

#

Not to mention the confusing margin it adds when trying to tell people to not format queries like that as they go β€œbut psycopg2 formats it like this"

#

As for bulk inserts than that's a meme, with executemany being slower than just a for loop of executions which is pithink

paper echo
#

the emphasis on portability doesn't make much sense to me, SQL portability is kind of a joke anyway. not to mention that DBAPI implementations are also different that, even if the queries were the same, you would still often have to rewrite code if for some reason you switched databases in your application

#

The row factory approach is pretty reasonable though

#

Not hard to type annotate either now that we have protocols. But obviously you can't annotate the result from a dynamic query that's generated at runtime

#

How do other typed languages handle that?

#

I know "how does it work in Haskell" is a meme here but how does "arbitrarily typed IO" work in haskell?

#

JSON, SQL, etc. which can return data of somewhat arbitrary types

flat gazelle
#

you just expect a certain inferred type and error/return Nothing if it does not fit

#

haskell read works like that

hs>(read "4.0"):: Int
*** Exception: Prelude.read: no parse
hs>(read "4.0"):: Float
4.0
paper echo
#

I see

#

So, something like that isn't really possible with static type checking

#

Right?

flat gazelle
#

Elm has a slightly different system, where you essentially describe what structure you expect and it either fits and you get Some t, and Nothing otherwise. This pretty much allows you to do everything dynamic typing can. In haskell, you can afaik use optics for similar results.

#

if you mean statically typed SQL queries, there is postgres-typed, which can check whether all the types match based on schema, but IDK if that is what you mean

paper echo
#

row: Tuple[int, float, float] = cursor.fetchone()

#

There's basically no way to check this

flat gazelle
#

SQL is not turing complete, so it should be possible in at least some cases

#

postgres-typed can for queries known at compile time

#

once you get to dependent typing though, it gets somewhat messier

paper echo
#

Right, but in general you need to annotate the results of a query not for checking the results of the query but for making sure that the rest of the program knows what results you expect

#

Whereas in one of these typed languages the types you expect from the query actually determine runtime behavior

#

So even in Haskell you can't really check the types of an expression like that until runtime

#

(Unless you parse the SQL code itself)

flat gazelle
#

ye, haskell cannot leave typechecking until runtime, as there is no runtime representation of types

#

so you have to describe your schema somewhere

deft pagoda
#

what's happening here:

In [4]: def test(cls):
   ...:     def something(cls):
   ...:         print(dir(cls))
   ...:     cls.__init_subclass__ = something
   ...:     return cls
   ...:

In [5]: @test
   ...: class Test: ...

In [6]: class Test2(Test): ...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-14348d06b900> in <module>
----> 1 class Test2(Test): ...

TypeError: something() missing 1 required positional argument: 'cls'

I can't figure out why __init_subclass__ isn't being passed any arguments

junior moat
#

because something is a function, you need to call the protocol with __get__ to bind cls

peak spoke
#

You need to bind it to the class object

deft pagoda
#

i tried __get__(None, cls)

#

but had the same error

peak spoke
#

cls.__init_subclass__ = types.MethodType(something, cls) ought to work

junior moat
#

I did not know MethodType, I personnaly use something like:
cls.__init_subclass__ = something.__get__(cls, cls.__class__)

MethodType seems way cleaner πŸ™‚

deft pagoda
#

both of these work

junior moat
#

pick the one you prefer then πŸ™‚

deft pagoda
#

or not...:

In [28]: def test_deco(cls):
    ...:     def __init_subclass__(cls):
    ...:         print(cls)
    ...: 
    ...:     cls.__init_subclass__ = __init_subclass__.__get__(cls, cls.__class__)
    ...:     return cls
    ...: 
    ...: @test_deco
    ...: class Test:
    ...:     ...
    ...: 
    ...: class Test2(Test):
    ...:     ...
    ...: 
    ...: class Test3(Test2):
    ...:     ...
    ...:
<class '__main__.Test'>
<class '__main__.Test'>

__init_subclass__ isn't getting the correct argument passed in

junior moat
#

well, you bind __init_subclass within the test_deco you did at the begining

#

it needs to be bound again with Test2 and Test3

#

I don't think decorator are suited for what you do

deft pagoda
#

I've wrapped it with classmethod decorator:

def test_deco(cls):
    def __init_subclass__(cls):
        print(cls)

    cls.__init_subclass__ = classmethod(__init_subclass__)
    return cls

@test_deco
class Test:
    ...

class Test2(Test):
    ...

class Test3(Test2):
    ...
#

this works

junior moat
#

ho nice

deft pagoda
#

i'm not sure what magic it's doing, but i'll dig into it later

junior moat
#

I was going to suggest using a metaclass if you needed to add a function to the most derived impl of an inheritance

deft pagoda
#

well, i have a metaclass solution to this hacky thing I'm doing

#

but the decorator solution is simpler

#

if I can get the methods to bind correctly

junior moat
#

this is hwo it is implemented, I've not thought of using the descriptor this way

deft pagoda
#
class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc

they give this as the descriptor of classmethod

junior moat
#

yep

deft pagoda
#

here's the thing:

from inspect import signature

def parse_signature(signature):
    return str(signature)[1:-1].split(', ', 1)[1]

def additive_init(cls):
    def __init_subclass__(cls):
        def add_parent_init(init):
            self_args = parse_signature(signature(init))
            parent_args = parse_signature(signature(cls.__base__.__init__))

            globals_ = {'init': init, 'cls':cls}
            locals_ = {}
            wrapper = f"""
            def wrapper(self, {parent_args}, {self_args}):
                super(cls, self).__init__({parent_args})
                init(self, {self_args})
            """
            exec(dedent(wrapper), globals_, locals_)

            return locals_['wrapper']

        cls.__init__ = add_parent_init(cls.__init__)

    cls.__init_subclass__ = classmethod(__init_subclass__)
    return cls

@additive_init
class Person:
    def __init__(self, name): self.name = name

class Cyborg(Person):
    def __init__(self, version): self.version = version

class Android(Cyborg):
    def __init__(self, model): self.model = model

print(signature(Android))  # (name, version, model)

Just a way to add inits from subclasses so you don't have to keep re-typing it all

junior moat
#

well, i have a metaclass solution to this hacky thing I'm doing

When you said hacky, I was actually far from the reality of what you were trying to achive πŸ™‚

#

when you end up doing exec, IMO you're the level above hacky πŸ˜‰

deft pagoda
#

I think at some level of meta-programming exec is very useful and nearly necessary

junior moat
#

(TBH I don't have better to offer so not saying that you should NOT do it)

deft pagoda
#

dataclasses use exec as well -- most code generators will

junior moat
#

actually for parameter forwarding I prefer the django approach: they define only named args, and forward **kw to parent

#

the base class itself might not take **kw, so you get errors if some args are not known

peak spoke
#

namedtuples are the ones I know about using exec; when I had a problem with them the code was quite confusing to navigate while looking for the cause

faint wind
#

anyone know any java disord server i can join?

swift imp
#

Does anyone know how costly it is to add new fields to a numpy.struct_array?

paper echo
#

@deft pagoda attrs doesnt afaik

#

i dont know why dataclasses should use exec tbh

narrow meadow
#

здрастС

flat gazelle
#
import random
def random_key(w):
    a ,= random.choices(*zip(*w.items()))
    return a
```should about do it
teal yacht
#

forgot to unpack w.items()

flat gazelle
#

oops

#
In [49]: Counter(random_key(w) for _ in range(1000))
Out[49]: Counter({'B': 761, 'A': 239})

In [50]: w
Out[50]: {'A': 1, 'B': 3}
```with that it seems to work
lone wagon
#

How does machine learning work

radiant fulcrum
lone wagon
#

k

paper echo
#

ah interesting

#

that isnt exec'ing the class itself though

#

its some auxiliary thing

deft pagoda
#

looks like a class def to me:

attr_class_template = [
        "class {}(tuple):".format(attr_class_name),
        "    __slots__ = ()",
    ]
worldly venture
#

!unsilence

fallen slateBOT
#

βœ… unsilenced current channel.

peak spoke
#

Is there any reason to use eval(compile(...)) over a direct exec? (from snippet linked above)

safe hedge
#

As for bulk inserts than that's a meme, with executemany being slower than just a for loop of executions which is pithink
@radiant fulcrum Use the correct function then: execute_values. And the point is that even that basic SQL formatting is more than other libs seem to offer

ivory warren
deft pagoda
#

@ivory warren don't post in multiple channels for the same question, and this is not a help channel

magic turret
#

is it legal to crawl emails

#

I need b2c France mails.

undone hare
#

3.5.10 hype baby!

#

Yay!

#

Ya... y..

brave badger
#

Yay πŸ₯³

teal stone
#

What does it mean **kwargs?

magic python
deft pagoda
#

kwargs is short for keyword arguments

red solar
#

Has anyone been following the infinity constant proposal and can bullet point it for me? The thread won’t load for me for some reason 😦

undone hare
#

I haven't looked at the thread, but what about float('inf')?

red solar
#

I think they want a more standalone constant

deft pagoda
#

math has them too

#

but I haven't seen any other proposals

#

that is, math.inf

undone hare
#

To be honest, even defining INFINITY = float('inf') isn't too bad

deft pagoda
#

i use float('inf') a lot by itself

#

and -float('inf')

sacred tinsel
#

@red solar The proposal makes the following points:

  • It is also a fundamental constant (similar to True, False, and None), and should be representable as such in the language
  • Requiring a cast from float to string is messy, and also obviously less efficient (but this performance difference is likely insignificant)
    • Further, having a function call for something that should be a constant is a code-smell; in general str -> float conversion may throw an error or anything else and I'd rather not worry about that.
  • It would make the useful property that eval(repr(x)) == x for floating point numbers (currently, NameError: name 'inf' is not defined)
#

The last point is further explained on the example of trying to serialize a list of floats by storing its repr and then evaling it

#

currently, it will throw the NameError

hearty monolith
#

Wait, which PEP is this?

sacred tinsel
red solar
#

Ah ty πŸ™‚

#

I agree with all of that, and hope it gets adopted (wonder how much code it would break tho)

#

Although ig if they added async as a keyword, they can do something for infinity

inland acorn
#

I am guessing they would keep float("inf") and give a deprication warning for a few versions

teal yacht
#

it shouldn't be deprecated tho

#

otherwise we should deprecate any cast from a literal

flat gazelle
#

float("inf"), not float(some_variable_that_resolves_to_inf). In a similar vein 4(6) raises a syntax warning

raven ridge
#

There'd be no reason to ever deprecate float("inf"), nor would this be a new keyword. It'd be a new builtin. Though assignments to inf would probably need to be banned, like they are for None and True and False, and that's backwards incompatible.

undone hare
#

I don't think it should be deprecated tbh

torn charm
#

anyone here a git genius?

undone hare
#

You could make it assignable actually

#

You'd keep backward compatibility

flat gazelle
#

Like NotImplemented

raven ridge
#

At the cost of incongruity with the other builtin singletons.

flat gazelle
#

Except NotImplemented

raven ridge
#

TIL.

peak spoke
#

Also Ellipsis

raven ridge
#

If it's allowed to be reassigned, I don't see any backwards compatibility concerns.

noble birch
#

is there a way to connect to the web via python (not like with sockets) to check for example if an URL exists?

zenith topaz
#

What if I based my code on there being a possible nameerror on inf

noble birch
#

what?

pliant tusk
#

@noble birch requests

#

@zenith topaz then it wouldn’t be backwards compat

noble birch
#

@pliant tusk i tried with urllib but it doesn't work

#

),:

pliant tusk
#

What’s your goal?

noble birch
#

to check if an URL exists

#

like try (function to connect to an URL) except print("URL doesn't exist")

pliant tusk
#

Yea, use requests and catch the ConnectionError

noble birch
#

how do i use requests?

#

is there a library to import?

pliant tusk
#

def check_url(url):
  try:
    requests.get(url)
    return True
  except:
    return False
pearl river
#

is there a library to import?
@noble birch yes, it's called requests πŸ˜›

radiant fulcrum
#

you could just low key use the status code

#

its not gonna error

pearl river
#

you'd also need to install it - requests is not a standard library.

Also, now that I notice, this is #internals-and-peps , not a help channel. Might want to move to one.

unkempt rock
#

is there a library to import?
@noble birch

#

oops

#

i meant to say

#

that

#

you should go to your command promt and type ' pip install requests '

unkempt rock
#

So basically my friend says he knows the least coding out of my Friend group is really hesitant to coding in general. Btw we’re all cs majors so how should I persuade him to code without being too preachy ??

feral cedar
#

if you're all cs majors you probably shouldn't need motivation to code

unkempt rock
#

if you're all cs majors you probably shouldn't need motivation to code
@feral cedar hmmm how so I’m just wondering

#

I guess it’s embedded into our cs instruction in college anyway

#

Well my friend Is the kind to get perfect scores on ap computer tests yet says he β€œforgot” all the code techniques when it comes to working on a project

raven ridge
#

shrug he'll probably wind up dropping out or changing majors. Or focusing entirely on the math theory behind CS and never learn to code well. If he doesn't want to learn to code, you're not going to be able to talk him into it.

#

That's all off topic for this channel, though. #career-advice is probably the best channel for it.

unkempt rock
#

shrug he'll probably wind up dropping out or changing majors. Or focusing entirely on the math theory behind CS and never learn to code well. If he doesn't want to learn to code, you're not going to be able to talk him into it.
@raven ridge no he says he wants to pick up on python and some js with discord.js but thru working with him in a casual group project , he has a really laissez faire approach and hardly ever intervenes unless the product looks β€œoff” in his mind

pliant tusk
#

@radiant fulcrum it errors for invalid urls (based on the dns response afaik)

pseudo cradle
#

@unkempt rock Sounds like management material

unkempt rock
#

Ye what if I should suggest my pap to go into business idk....he says he hasn’t really extrapolated too much into cs and/or programming in general. My friend actually put his work in progress cs50 certification on LinkedIn. He didn’t even finish it yet. Like he just does it for the resume so how should I tell him nicely? Sorry if I’m too concerned about his activity @pseudo cradle

frosty oyster
#

Anyone around? I have a question about Python's hash() function and whether I should use an alternative.

charred barn
#

what are you trying to do?

#

i'd not rely on the hash function for anything outside of implementing your own __hash__ methods.

mint forge
#

How do I uninstall python 32 bit

charred barn
feral cedar
#

just... uninstall it

mint forge
#

it also has an change option can I use that to make it into 64 bit

feral cedar
#

this isn't really the channel for this

teal stone
#

What is the meaning of backtracking and how is it done?

@Beginner(slow-witted)

graceful saddle
#

Hey Developers I am a 2nd year student and i want to build a system like jarvis of iron man. So i need your help I don't know where to start and what to do.

slim island
#

This channel is usually a bit more focused and specific than that. Maybe an off topic channel would be better?

half wolf
#

@graceful saddle so first you must revolutionize AI research :) Maybe scale down your ambition a bit.

lyric marsh
#

can anyone send me a pygame code to make a space invaders game using pygame

boreal umbra
#

Guido has this great hot take from 2002: "filter and map should die and be subsumed into list comprehensions"

odd ether
#

@cunning scaffold this channel isn't the place for that

flat gazelle
#

honestly, map(f,*a) is cleaner than (f(*v) for v in zip(*a)

sacred yew
#

map is only good if the mapping is already a function

#

and not a lanbda

boreal umbra
#

@flat gazelle it's more concise but I think the second one is a bit more obvious

#

granted both are entirely non-obvious if you're not familiar with that usage of the star operator.

#

I guess I wouldn't reject the first one if it was in a PR

#

I also use filter occasionally, but I feel like yield from filter(z, y) is more elegant than yield from (x for x in y if z)

teal yacht
#

strong disagree on that comprehension being more obvious than the map, but we all have different tastes i guess

swift imp
#

Is there a way to block child class from inheriting parent docstring?

#

At work we subclass DataFrames in a few cases and inheriting the docstring just makes the help so verbose

red solar
#

Lol u reminded me of a case where someone was annoyed that docstring didn’t get inherited - i’ll ping u if I find it

#

(Although there’s probably easier ways)

grand crag
#

If you control the parent class, override __init_subclass__ and set the child's __doc__ attribute to "". I've never tried it, but I think it could work.

#
>>> class T:
...     """This is a docstring"""
...     @classmethod
...     def __init_subclass__(cls, **kwargs):
...             cls.__doc__ = ""
...             super().__init_subclass__(**kwargs)
... 
>>> class M(T):
...     pass

class T(builtins.object)
 |  This is a docstring

class M(T)
``` It seems to work here. The docstring doesn't appear for `M`.
swift imp
#

Nice, thanks!

dense needle
#

hello !

#

can anyone help me i dont know how this code works i dont know the benefit of it

#
for i in range(len(supplies)):
       print('index'+ str(i) +'in supplies is :'+supplies[i])```
hasty thistle
#

I'm assuming you got it from automate the boring stuff?

#

it's teaching you about loops, strings and indexing

dapper yoke
#

Hello
Pls answer these both questions
How do I store the mid value of my string into a new matrix starting from 0,0 then 0,1 So on...

  And

How do I store the values of a matrix into a list
Can I say x=[ [1][2],[3][4]]
Will x be having the 2 elements of my matrix?

boreal umbra
dapper yoke
#

Thankyou

torpid trellis
#

anyone have any experience with boto3

trail ridge
#

Hi, I just started learning about linked lists. I am printing what I stored in the linked list and the element at 0th index shows "None".

paper echo
#

@trail ridge this sounds like a better question for #algos-and-data-structs . however you should at least show your code so that other people can help. nobody can guess what is wrong with your code

safe hedge
#

Is the following an acceptable pattern:

class MyClass():
    def __init__(self, arg1, arg2, arg3, **kwargs):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
        self.other_class = OtherClass(**kwargs)
        
    def __enter__(self):
        self.other_class.__enter__()
        return self
        
    def __exit__(self, exc_type, exc_value, traceback):
        self.cleanup_func()
        self.other_class.__exit__()
gritty pebble
#

why wouldnt you subclass OtherClass

safe hedge
#

Because this is just a really simplified version

#

Imagine if OtherClass was open(filename)

paper echo
#

we've been kind of 50/50 on whether "is this pythonic" questions are allowed

#

as long as they're sophisticated and not "how do i write function"

safe hedge
#

Yeah I felt this was more conceptual than a directed help

paper echo
#

that said no i dont think there's anything wrong with it

#

there are lots of reasons why you wouldnt want to subclassOtherClass, e.g. maybe you have 3 other_class-like things

#

(the big problem i see here is lack of attrs usage πŸ˜‰)

#

but for real yes its fine, however you should pass all those args in exit other_class.__exit__(exc_type, exc_value, traceback)

safe hedge
#

Yeah I realised that after

#

What exactly would attrs do here though?

paper echo
#

im also not a fan of the **kwargs here

#
class MyClass():
    def __init__(self, arg1, arg2, arg3, other_thing: OtherClass):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
        self.other_thing = other_thing
        
    def __enter__(self):
        self.other_thing.__enter__()
        return self
        
    def __exit__(self, exc_type, exc_value, traceback):
        self.cleanup_func()
        self.other_thing.__exit__()
#

actually attrs isnt that useful unless you want type annotations, in which case it saves you a lot of duplicated typing

safe hedge
#

I wouldn't normally use kwargs. Again I was trying to create a really generic example

paper echo
#
@attr.s
class MyClass():
    arg1: int = attr.ib()
    arg2: float = attr.ib()
    arg3: bool = attr.ib()
    other_thing: OtherClass = attr.ib()
        
    def __enter__(self):
        self.other_thing.__enter__()
        return self
        
    def __exit__(self, exc_type, exc_value, traceback):
        self.cleanup_func()
        self.other_thing.__exit__()
safe hedge
#

I'm unsure on whether it's better to allow someone to pass the composite class or create it within the init

paper echo
#

i definitely prefer the former. you can always create a default one if they pass None

safe hedge
#

For example in a situation where the composite class is something you wouldn't expect the end-user to ever directly interact with

paper echo
#

fair enough. if the wrapped class is never meant to be created on its own then it's fine

#

plus creating classes to pass as parameters to other classes feels very clunky and Java-esque so i don't blame you for wanting to avoid it

#

but sometimes it really is the best way to do things

#

i'll take clunkiness if it means avoiding wasteful code duplication

#

or if it means avoiding a kwarg dumpster

#

i really dont like **kwargs in user-facing functions unless it's very obvious what said kwargs are being passed to

safe hedge
#

I have one case where there is a sort of 1-1 mapping of inner class to wider class, but which inner class you want is dependent on the outer class. Does that make sense at all haha

paper echo
#

hm

#

why

#

maybe something like this?

@attr.s
class MyHttpxClient:
    sansio_client: MyClient = attr.ib()
    httpx_client: httpx.Client = attr.ib(factory=httpx.Client)
safe hedge
#

Like, I have a generic outer and generic inner. But then I have a specialised outer which uses a subclassed inner with one method overidden

paper echo
#

can't the outer just wrap the one special method

#

instead of making a whole customized version of the inner

safe hedge
#

The outer class would then override a method on a class it's being passed?

paper echo
#

no of course not

safe hedge
#

Like:

class InnerA():
   ...

class InnerB(InnerA):
    def overridden(self):
         #stuff

class OuterA():
    def __init__(...):
        self.inner = InnerA()

class OuterB(OuterA):
    def __init__()
         self.inner = InnerB()
#

Does that explain what I'm talking about?

paper echo
#
@attr.s()
class OuterThing:
    inner_thing: InnerThing = attr.ib()

    def frobulate(self, x: float) -> float:
        return self.inner_thing.frobulate(x / 100.0)

versus

class SpecialInnerThing(InnerThing):
    def frobulate(self, x: float) -> float:
        return super().frobulate(x / 100.0)

class OuterThing:
    inner_thing: SpecialInnerThing
    def __init__(self):
        self.inner_thing = SpecialInnerThing()

    def frobulate(self, x: float) -> float:
        return self.inner_thing.frobulate(x)
safe hedge
#

I think what I probably want is for the outer class to define an inner class factory?

paper echo
#

maybe. which in python of course is just a class

#

it really depends on how your application is set up

#

consider what your public interfaces are

#

what your data contracts are

woven apex
#

hi everyone

wide shuttle
#

Hello Nurken

woven apex
#

does anyone know, how to create paint program at Python?

wide shuttle
#

That's not really a question for this channel; we try to reserve this channel for discussing the Python programming language itself, from a higher-level and more abstract perspective.

#

We do have a lot of other channels where you can ask your question, like #python-discussion, or help channels

gleaming rover
#

plus creating classes to pass as parameters to other classes feels very clunky and Java-esque so i don't blame you for wanting to avoid it
@paper echo why do you think so?

woven apex
#

oh sorry

paper echo
#

@gleaming rover it's just not something you see often in python

#

and classes like BeanFactoryFactory are a meme

gleaming rover
#

@gleaming rover it's just not something you see often in python
@paper echo wait, let me clarify

#

did you mean classes, as in type objects (as opposed to instances)?

paper echo
#

no sorry i mean instances, but things like this OuterThing(InnerThing(a, b), c)

gleaming rover
#

oh hm

#

isn't that basically dependency injection

paper echo
#

yes

gleaming rover
#

I actually don't have much Java experience so I'm not sure about that part of your statement, but why do you think it's clunky

paper echo
#

i dont have much java experience either so i might be treating it unfairly

#

its clunky because you just dont see it that often in libraries

#

but i think its a perfectly valid, maybe even underused, pattern

gleaming rover
#

hm.

#

now that you mention it

#

why is dependency injection so uncommon in Python

#

or is it just in the stuff I use

paper echo
#

(fwiw i dont like dependency injection, id rather just wrap stuff)

#

you see things like factory= very occasionally

#

but again why do that when you can just write a wrapper function

#

its a good question though

unkempt rock
#

Whats future module?

safe hedge
#

It's composition

#

Personally I prefer composition to inheritance where possible

gleaming rover
#

Whats future module?
@unkempt rock basically, a way to apply changes that will be mandatory in a future version of Python, but optional in the one you're running

unkempt rock
#

Oh

raven ridge
#

future, or __future__ ?

#

__future__ is part of the Python language, a way to opt into backwards incompatible language changes before they become mandatory. future is a 3rd party module that tries to help you write code compatible with both Python 2 and Python 3.

deft pagoda
#

and a Future is...

raven ridge
#

entirely different, but that's in futures, not future or __future__, heh

unkempt rock
#

I want to override gettattr but my mul does a deepcopy which causes gettattr to throw an error. I don't want to override deepcopy as I don't feel I can reliably duplicate what that does. Anyone know if there's another solution?

brittle yew
#

anyone here use buildozer???

wide shuttle
#

@unkempt rock Does your __getattr__ raise an AttributeError for nonexisting attributes? If not, that's probably what's causing the issue you have.

#

Normally, when you access a non-existing attribute, you'll get an AttributeError. However, if you overwrite __getattr__, that method gets called and it returns something. If the function does not hit an explicit return, it will return None implicitly. Take a look at this:

#

!e

class Foo:

    def __getattr__(self, attr):
        if attr == "bar":
            return "some result"


f = Foo()
print(f"This will print 'some result' as expected: {f.bar!r}")
print(f"This will print `None`: {f.something_else!r}")
fallen slateBOT
#

@wide shuttle :white_check_mark: Your eval job has completed with return code 0.

001 | This will print 'some result' as expected: 'some result'
002 | This will print `None`: None
wide shuttle
#

I think this is what happening in your case

#

If you raise an AttributeError, copy.deepcopy will not complain:

#

!e

import copy


class Foo:

    def __getattr__(self, attr):
        if attr == "bar":
            return "some result"

        raise AttributeError

f = Foo()
copy.deepcopy(f)
fallen slateBOT
#

@wide shuttle :warning: Your eval job has completed with return code 0.

[No output]
unkempt rock
#

hmm. now i get max recurision.

#

def getattr(self, key):
if key in self.kwargs.keys():
return self.kwargs[key]
else:
# return None
raise AttributeError

#

but the deepcopy error is gone. however now it wont deep copy

peak spoke
#

You have to use the attribute access from a parent class that doesn't modify it or it'll call itself every time

unkempt rock
#

i thought raising the attribute error stopped that?

#

or was supposed to

deft pagoda
#

self.kwargs <- if kwargs isn't an attribute you'll be calling getattr again

unkempt rock
#

sorry . yes probably not best name. but it is defined on init

#

and just takes the kwargs that are passed

wide shuttle
#

In this case, the object won't be initialized using teh __init__, so that attribute won't exist (yet)

#

So, everytime it's trying to check if an attribute exists before that kwargs becomes available, it will get in a __getattr__ loop

#

Maybe if you do it like this (or handle the KeyError), it will work:

    def __getattr__(self, attr):
        kwargs = super().__getattribute__('kwargs')
        if attr in kwargs:
            return kwargs[attr]

        raise AttributeError
unkempt rock
#

class MyClass(object):
def init(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs

def __mul__(self, other):
    reproducer = []
    for i in range(other):
        reproducer.append(copy.deepcopy(self))
    return reproducer

def __getattr__(self, key):
    if key in self.kwargs.keys():
        return self.kwargs[key]
    else:
        # return None
        raise AttributeError
#

ive deleted some stuff

#

but essentiall i want my cake and eat it

#

i feel if i wrote a deepcopy that did what deep copy does. it may work. but i dont trust i can do that

wide shuttle
#

And the suggestion I gave above?

#

Does that work?

unkempt rock
#

essentially if prop not exist. look for it on the nest array. gonna try your tip now. 5 mins

#

woah!

#

5 hours last night 😦 then i gave up

#

thank you so much

#

incredible

#

thank you so much . i've read the code and completely understand now what you are doing. I don't know why that wasn't obvious to me. thanks

deft pagoda
#

I'm pretty sure I've burned myself with getattr a few times

wide shuttle
#

For me, it's partly because None is just a valid, regular return value that's returned implicitly. My first instinct is to write a __getattr__ that just handles the dynamic attributes that I want to handle, but, if you're not careful, now every attribute exists dynamically but most of them just return None.

#

You don't notice this a lot until you hit something that relies on that AttributeError signal to be raised.

#

And, in this case, deepcopy throws a curveball as well, as you'd expect kwargs to exist from the start but it only exists after it's been deepcopied.

unkempt rock
#

can i credit you?

#

link to ur blog or something on the code comment

#

?

wide shuttle
#

I don't really have anything to link to. Most of the free time I have for Python I spend on this community.

#

And I don't particularly need to get credit, as it were just a few lines and I integrated @peak spoke idea as well

unkempt rock
#

big thanks to all that helped. I'll link the discord group. very grateful

#

I cant now get dot notation on extra props. which is so cool

#

*can

stuck barn
#

how do i call a function given as a parameter

peak spoke
#

I don't think anyone in communities like this, SO etc. really expects you to credit them even while technically it's all rights reserved unless stated otherwise

hexed maple
#

@stuck barn wdym
like a callback ?

stuck barn
#

you would do myFunc(func) and it executes the function func

#

thats what i need

unkempt rock
#

func()

hexed maple
#

ok

stuck barn
#

it executes the parameter

#

which can vary

hexed maple
#

u are passing the func by name (Func("func")) or the object itself (Func(func))

stuck barn
#

yes

hexed maple
#

i mean how are u passing it
like Func("func") or Func(func)

stuck barn
#

second one

#

@hexed maple

hexed maple
#

ok

raven ridge
#

Python has functions as first order objects. You can pass a function just like passing any other variable. Any variable that holds a function can just be called like a function.

hexed maple
#

^^

stuck barn
#

wait so if i do h = func then i can do h() ?

unkempt rock
#

h = func

raven ridge
#

!e ```python
x = print
x("hello")

def say_hi(printer):
printer("hi")
say_hi(print)

fallen slateBOT
#

@raven ridge :white_check_mark: Your eval job has completed with return code 0.

001 | hello
002 | hi
stuck barn
#

yes i saw that

#

typo

wide shuttle
#

@peak spoke SO does list a license for user contributions, but some examples and snippets are fairly generic. I doubt you could really claim "copyright" on them. Anyway, we're getting a bit off-topic, but you're right about people probably not expecting credit.

unkempt rock
#

Although you could do h = func() if func() returned another function

hexed maple
#

!e

fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

hexed maple
#

ohh

#

here is a very simple example

def a(func):
    if callable(func):
        func()
    else:
        pass
def b():
    print("it works")

a(b)
#this wont
a("hi")
raven ridge
#

it's a staff superpower to use !e in discussion channels.

hexed maple
#

i shall wield it someday

raven ridge
#

@stuck barn for completeness's sake: a function is an object. That object is able to be called. The name of the variable that refers to that object is irrelevant. The statement def foo(...): creates a new function object and assigns it to the name foo. It's syntactic sugar for a regular assignment. Once it has been assigned, it can be reassigned to a new name, or passed as an argument, or whatever.

deft pagoda
#

I wish there was a std library of common decorators

raven ridge
#

It's the function object itself that has something magical about it - callability - not the original name that it was defined with. The only thing special about the name that it was defined with is that it's stored and introspectable, but that's really only for debugging purposes and to give a nice repr

half wolf
#

The nice repr is hugely important though. I really wish lambdas had reasonable reprs.

gritty pebble
#

It would be cool if there was a bitset/bitarray in the standard library

undone hare
#

What about

#

!d array.array

fallen slateBOT
#
class array.array(typecode[, initializer])```
A new array whose items are restricted by *typecode*, and initialized from the optional *initializer* value, which must be a list, a [bytes-like object](../glossary.html#term-bytes-like-object), or iterable over elements of the appropriate type.

If given a list or string, the initializer is passed to the new array’s [`fromlist()`](#array.array.fromlist "array.array.fromlist"), [`frombytes()`](#array.array.frombytes "array.array.frombytes"), or [`fromunicode()`](#array.array.fromunicode "array.array.fromunicode") method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the [`extend()`](#array.array.extend "array.array.extend") method.

Raises an [auditing event](sys.html#auditing) `array.__new__` with arguments `typecode`, `initializer`.
undone hare
#

bytearray is also a thing

gritty pebble
#

That's not the same thing

undone hare
#

You could make an array of bool

#

Probably not that efficient, but still

gritty pebble
#

Yeah, the use case where I could have used something like this I ended up using bytearray which was much better then a list

#

Imo it seems like something that would fit nicely in collections but I'm not sure if it's too niche of a data type

mighty viper
#

can i host online socket server from heroku

#

to send and recv data from the server

boreal umbra
south egret
#

WHy am i getting this error?

#

if i shutdown and restart then it works

#

but am not understanding why am i getting this error

pallid meteor
#

its not an error

#

the cells are running

#

also, this isnt the proper channel to ask about this

south egret
#

ok

#

Still can u tell me why when i click on run it doesnt work

charred wagon
timber bobcat
#

Ayo anyone knows if there any way to implement a key of some sort to only be able to run ur python script on one computer ? Let's say for example i put a program for sale and i dont want it to just be passed on so easily is there a way i can add something to my program to only run on that particular computer ?

half wolf
#

There are many ways. The best way is of course to not ship your software at all and instead have it on your own server. After that you should use a compiled language, then if you finally decide to use python then it's super easy to bypass and you should learn to live with that.

paper echo
#

Can you even do that in a compiled language

boreal umbra
#

@timber bobcat you can use PyArmor, but it's not likely that anyone will want to claim credit for your exact code.

paper echo
#

I think their concern is piracy

boreal umbra
#

Ah

timber bobcat
#

yeah i already considered PyArmor so they cant read the files , but my concern is that one guy buys it and he just spreads it like covid-19

#

i was wondering if there was a way to make the program only run on one computer

paper echo
#

No matter what language you use, basically the only way to stop that is to use a one time registration key

#

Consider that even professional and very expensive software like Adobe creative suite and Microsoft word can be cracked

timber bobcat
#

yea i know

#

well that sounds interesing the one time registration key

grave jolt
#

or use the Software As A Service model

paper echo
#

I'm actually not entirely sure how license keys work for software like that. I suppose the license key is sent to a server for approval, and then some kind of local confirmation of approval is stored

#

Or you can have the program connect to the Internet to check the key upon start up

#

At which point yes, it becomes much easier to hack apart a python program than a compiled C++ program in order to get it to run without a valid key..

#

I also think that kind of start up check can result in being user hostile as it now requires an Internet connection in order to use the software

grave jolt
#

You could cache the check

timber bobcat
#

my program needs internet anyways to run

paper echo
#

Maybe there are algorithms that let you use some kind of asymmetric encryption

timber bobcat
#

so it wont be a problem really

#

but tbh i dont think someone will go out of their way to crack my program if i implement a one time registration key

#

its just a bot for a phone game

grave jolt
#

that sounds ToS-breaking πŸ€”

timber bobcat
#

shhhh

grave jolt
#

Yeah, selling an automation bot for a game definitely sounds ToS-breaking

paper echo
#

!rules 5

fallen slateBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

timber bobcat
#

oh shiiiπŸ‘€

paper echo
#

Seems a bit ironic to worry about piracy when you're botting someone else's application

grave jolt
#

lmao

#

well, criminals wear body armor, right

paper echo
#

True

timber bobcat
#

well sorry for that one lads

#

kinda got overwhelmed and forgot bout the rules

vast dome
#

hi

timber bobcat
#

sup

vast dome
#

i joined

#

is this the general chat?

timber bobcat
#

the one above this one

vast dome
#

ok thanks but i think ill stay here

timber bobcat
#

that one

vast dome
#

anyways u should set a pic if u want i could search one for ya

#

welp-

timber bobcat
#

naahh thanks im coo

vast dome
#

imma just go read rules

timber bobcat
#

i think we should move to the general chat till the mods dont throw the mighty ban hammer uppon us

vast dome
#

kk

paper echo
#

@vast dome thanks for reading them, a lot of people dont even bother

#

(Not throwing shade)

vast dome
#

πŸ™‚

timber bobcat
#

ayy man i read em

paper echo
#

And yes @timber bobcat thank you as well

timber bobcat
#

just got a bit carried away

paper echo
#

Wasnt meant to be a jab at you

timber bobcat
#

oh

paper echo
#

Lots of people just ignore the rules and sometimes get upset when they are directed to the rules

#

You didnt do that so its all good

timber bobcat
#

oh yea i know people that do get hella angry

#

but im calm and understanding

supple karma
#

Hey my RTX 2060 is sitting at 60% usage while training a tensorflow bot. Why is tensorflow not maxing my card?

#

Latest version*

radiant fulcrum
#

because you're training AI and thats inherently load intensive

#

TF is doing what its supposed todo by making use of your GPU

supple karma
#

Oh. But surely it should use all of it?

radiant fulcrum
#

Normally other limitation

#

RAM, CPU bottle knecking it probably

supple karma
#

Hmm interesting. πŸ€”

radiant fulcrum
#

but equally you should remember the system GPU's like that are designed for are not the same as those used for AI

supple karma
#

CPU and system RAM is cool.
True. Very true.

radiant fulcrum
#

VRam aswell can be a limit

supple karma
#

Thats on 97%...

#

So that's probably why.

#

Wait nvm its on 37% weird

boreal umbra
#
try:
    from scipy.stats import binom_test
except ImportError:
    print >>sys.stderr, 'INFO: Could not import scipy (www.scipy.org): signtest is not available.'
#

this was apparently written in 2013

#

has that syntax for print ever been supported or does this person just think they're writing C++?

boreal umbra
#

so this is python 2?

peak spoke
#

that line at least

boreal umbra
#

I have a few good things to say about this file

#

for example, the author uses random.choice

grave jolt
#

that's some weird syntax πŸ‘€

peak spoke
#

I've made a config system for my app where values are accessed and set with class attribute access on classes directly at the module level so with the class

class Category:
    value: ... = ...

I can access the shared value from every module in my app with an import and all value gets synced to a file when set unless a method is used to delay it.
This works great, but I'm not sure about the design with classes and attributes, do you think it's fine or since the values are being modified at runtime some kind of an instance that gets passed around would be more fitting?

spark venture
#

how do i extract the most dominant color from any type of image in any format?

#

somewhat like spotify

unkempt rock
#

for example, the author uses random.choice
@boreal umbra is random.choice bad?

spark venture
#

thanks @unkempt rock!

boreal umbra
#

@unkempt rock no, random.choice is very good

#

The alternative is to use randint for the length of your list

unkempt rock
#

ah ok

boreal umbra
#

@unkempt rock (my responses are intermittent because I'm at work) random.choice is also better because it works for any container type. I think.

#

Let's see.

unkempt rock
#

No worries. I'll read your responses as they come.

boreal umbra
#

!e

bob = {1, 2, 3, 4, 5}
from random import choice
print(choice(bob))
fallen slateBOT
#

@boreal umbra :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "/usr/local/lib/python3.8/random.py", line 291, in choice
004 |     return seq[i]
005 | TypeError: 'set' object is not subscriptable
boreal umbra
#

Omg

#

It doesn't work for sets.

#

I'm so upset

burnt obsidian
#

Hey guys, I'm using the Youtube API Data
and i came to this error

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=ItsAleMazing&key=AIzaSyAM3YG7QAGmwiz36vKksbalOwKFKGisxVk%0A&alt=json returned "The request cannot be completed because you have exceeded your <a href="/youtube/v3/getting-started#quota">quota</a>.">

my code:

        addLog('(type=id) Getting a request of Channel ID of "' +  username + '" ...')
        time.sleep(5)
        request = youtube.channels().list(
                                            part="id",
                                            forUsername=username
                                        )
        addLog('(type=id) Got a request of Channel ID of "' + username + '" ...')
        
        addLog('(type=id) Executing the Request of "youtube.activities" of [' + username +']...')
        time.sleep(5)
        response = request.execute()
        time.sleep(5)```

May someone help me ?
the error come from this line  `response = request.execute()`
boreal umbra
feral cedar
#

steler it works on sequences

solemn jewel
#

hey so for matplotlib.pyplot why do i have to call plt.show()? can't it just pop up automatically for me?

gleaming rover
#

hey so for matplotlib.pyplot why do i have to call plt.show()? can't it just pop up automatically for me?
@solemn jewel depends on where you're running it

#

some environments do, automatically

#

e.g. if you're running in terminal

#

it doesn't

#

so that you can apply all your changes before you show

solemn jewel
#

oh ok

#

sorry

unkempt rock
#

Its weird that random.choice doesnt work on sets

feral cedar
#

not really

gleaming rover
#

well, if the container is unordered, you don't really have a way to get an element that you can prove is random

unkempt rock
#

Makes sense

feral cedar
#

it needs a sequence

unkempt rock
#

A set is really more like a dictionary with just keys I guess

charred wagon
#

I imagine random.choice gets a random integer in the range of the sequence length and uses that as the index to get a random element. Don't know if that's actually true

#

That's always been my explanation to myself for why things likes sets will not work

ebon jasper
#

probably, sounds about right

#

not sure if this is the right channel but, how do you write a function that can clear frames in tkinter?

gleaming rover
#

not sure if this is the right channel but, how do you write a function that can clear frames in tkinter?
@ebon jasper #user-interfaces

ebon jasper
#

thanks

cursive gazelle
#

I imagine random.choice gets a random integer in the range of the sequence length and uses that as the index to get a random element. Don't know if that's actually true
@charred wagon this is true

boreal umbra
#

steler it works on sequences
@feral cedar I can understand based on the error message why the implementation doesn't work for sets, but conceptually getting a random item from a set isn't hugely different from getting one from a list.

gleaming rover
#

@feral cedar I can understand based on the error message why the implementation doesn't work for sets, but conceptually getting a random item from a set isn't hugely different from getting one from a list.
@boreal umbra is it not...?

boreal umbra
#

The very concept of getting a random item from an ordered sequence is agnostic to the fact that that sequence is ordered.

gleaming rover
#

in particular, for a set, there is no way to refer to any specific element

boreal umbra
#

Right

gleaming rover
#

it's not about it being ordered, really, I think

boreal umbra
#

Sets have a method that will return a random element and remove it from the set. I don't remember the name for sure but it might be pop.

gleaming rover
#

Sets have a method that will return a random element and remove it from the set. I don't remember the name for sure but it might be pop.
@boreal umbra it is pop, but it doesn't return a random element

#

it returns an arbitrary element

boreal umbra
#

Point taken.

safe hedge
#

Thinking a bit more about the discussions I had in here yesterday with __enter__ and __exit__, is there some guidance for how an object with those defined is meant to behave. Like it seems that there is not consistency since with can be used without as i.e. with threading.Lock():. Is it really just a case of good documentation to ensure the correct usage of your class with a context manager?

sacred yew
#

usually it should be somewhat obvious when you need as

#

since that's when you actually want to use the object

spark magnet
#

@safe hedge the only semantic is that __enter__ should will be called on entering, and __exit__ on exiting. it can be used for resource acquisition, or exception management, or other things.

safe hedge
#

@spark magnet So effectively yes any specific usage/behaviour is only really covered by documenting?

paper echo
#

yes @safe hedge

unkempt rock
#

hey guys

warm spire
#

sup

unkempt rock
#

Hi

#

I need help

undone hare
unkempt rock
#

why hasattr func even exists ?
can't we just use getattr and compare if its something or not ?

sacred yew
#

compatibility probably

#

python has a lot of builtin functions

paper echo
#

@unkempt rock because then you have to always decide on a sentinel value

modern night
#

@unkempt rock you could do getattr(obj, attr_name, None) but if the object does have that attribute and its value is just None you will get false positives you need a default for your method and there is always a chance that that object has that value as its atribute

paper echo
#

hasattr is also implemented directly in C

#

and a lot less ugly

radiant fulcrum
#

@paper echo only thing with hasattr compared todoing it with getattr is that it wont get methods

#

from what ive found

modern night
#
class Foo:
    def bar(self):
        ...

        
hasattr(Foo(), 'bar')
True```works for me
radiant fulcrum
#

hmm

paper echo
#

what do you mean it wont get methods?

radiant fulcrum
#

idk now lol, ive had issues in the paste where it wont get methods without doing say bar()

paper echo
#

!e ```python
class Foo:
def bar(self):
...

foo = Foo()
print(type(getattr(Foo, 'bar')))
print(type(getattr(foo, 'bar')))

fallen slateBOT
#

@paper echo :white_check_mark: Your eval job has completed with return code 0.

001 | <class 'function'>
002 | <class 'method'>
boreal umbra
#

hasattr also lets you use strings, and you can't use variables with the dot operator

#

So it opens up a lot of functionality that's cleaner to write than having lots of try-catch AttributeError

spark venture
#

What exactly is Ellipsis/... in Python?

swift imp
#

its a shortcut for slicing

#

say you had an 10 dimensional ndarray called x if you wanted to slice say 2,5,10 and everything inbetween 5 and 10 instead of doing x[2,5,6,7,8,9,10] you could do x[2,5,...,10]

#

or something like that, I don't fully understand it myself but its for slicing high dimensional stuff

spice pecan
#

numpy arrays use it as a filler for multidimensional slices, yeah

#

IIRC the only use it has in the stdlib are a couple of (relatively) recent cases in typing

paper echo
#

wait... what

#

i actually didnt know you could slice a numpy array with ellipses

#

that's also a 3rd party library co-opting it

#

as i understand it, the ellipsis is just a no-op expression

spice pecan
#

It's a mystery, really

paper echo
#

i wonder when it was added

spice pecan
#

It has existed long before the ... literal apparently, and I don't really see how that would be useful?

paper echo
#

really?

#

Ellipsis existed before ...?

spice pecan
#

yeah, we found that out one of the last times Ellipsis came up in this channel

paper echo
#

!e ```python
x = list('abc')
print(x[...])

fallen slateBOT
#

@paper echo :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: list indices must be integers or slices, not ellipsis
paper echo
#

i dont think Ellipsis itself is used anywhere in the CPython source

peak spoke
#

It's a nice placeholder for code in stubs or when you're planning to implement something, apart from that I think only typing uses it

paper echo
#

maybe ... is

spice pecan
#

The stdlib doesn't support Ellipsis anywhere outside of typing

paper echo
#

yeah but ... and Ellipsis pre-date those uses @peak spoke e.g. with Protocol

paper echo
#

is it like @/__matmul__ where it was added just for 3rd party libs to use?

spice pecan
#

Pretty much, yeah

paper echo
#

!e ```python
print(dir(Ellipsis))

fallen slateBOT
#

@paper echo :white_check_mark: Your eval job has completed with return code 0.

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
peak spoke
#

Don't think there's much to be found about it when the commit that added the object is from 96

spice pecan
#

PSF Mysteries Unsolved

peak spoke
#

Looks like it was added in 1.4, there's a comment with 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-( in a modsupport.h file but not really sure what that refers to (probably something during development as 1.3 doesn't have either of them in the source)

peak spoke
#

the PEPs and issue tracker are fairly easy to go through for features etc. but there's not much to be found for python 1

red solar
#

it's always fun looking through the git repository back in early 2000 though (or whenever they put it on github)

paper echo
#

there are git commits going back into the 90s

#

github has the whole commit history

#

or a lot of it

peak spoke
unkempt rock
#

how can i make like "wait for some event" in python... ?
do i need to use async and await ?
or what..?

radiant fulcrum
#

@paper echo Thanks for that Talk :P Probably wouldnt have found it without it but damn thats pretty nice

paper echo
#

Classes are really hacked in at the last moment.
It should be possible to use other object types as base classes,
but currently it isn't. We'll see if we can fix that later, sigh...
lol

radiant fulcrum
#

So ive learn this from the talk: Kill Pickle, Fix imports

sacred yew
#

wait whats wrong with pickle

gritty pebble
#

Arbitrary code execution stuff

narrow kettle
#

hmm, i suppose pickle can serialize callables

#

id never reallly thought about that, thats intriguing

spark magnet
#

no, it doesn't pickle code

#

but it will run whatever code you tell it to that it can find in the process.

unkempt rock
#

I never read an explanation of how pickle is insecure, just knew that it was.

#

Typically I will deconstruct properties fromk objects and put them into json. Then the program that loads the json, will construct objects again using that data. There are situations where that isnt realistic I think, but I do that pretty often.

solar delta
#

Right ^ state in methods/classes is a bad idea but for 3rd party objects pickles r fine

#

note; some modules don't work well with pickle; like XGBoost doesn't return the same object you stored

spark magnet
#

@solar delta what do you mean, "not the same object"?

#

it's in a new process, isnt it? so it can't literally be the same object

solar delta
#

if you pickle an XGBoost model that has been trained the results won't come out the same if you have the same seed.

#

It works fine with Gradient boosting from sklearn though..

leaden sphinx
#

Can I post a slightly more advanced question here?

sacred yew
#

sure

#

as long as it fits channel topic

charred wagon
#

@leaden sphinx There are dedicated channels for Python help. In fact, it's our entire help system #β“ο½œhow-to-get-help. Your question could also go in a topical channel, specifically #databases. This channel is not appropriate because it is a discussion channel, not a help channel.

leaden sphinx
#

Thanks

red solar
#

In fairness to pickle, it is noted that you should only use it on trusted data

unkempt rock
#

k

misty tiger
misty tiger
undone hare
#

It seems like GvR commited python libraries before all the C code

grave jolt
#
class CheckAppearance() = LabelAppearance():

class BaseButton() = NoReactivity(), LabelAppearance(), Define():

I'm glad we have different inheritance syntax...

true hollow
#

me too

brave badger
#
class Foo is a BaseClass1 and a BaseClass2 and a BaseClass3:
#

I jest

true hollow
#

are we writing cursed code at this point pithink

pliant tusk
#

i wonder if py class Foo(Base1 and Base2): could be hacked together using metaclasses

brave badger
#

You'd probably have to mess with the mro

pliant tusk
#

basically make and return a new class that has both Base1 and Base2 in its mro

#

dont know if thats possible tho

peak spoke
#

Don't think you can, since the and will evaluate them separately

pliant tusk
#

could use inspect to get the context and do it that way

#

on __bool__ call

brazen jacinth
#

python programmers often ask themselves if they can, not enough times if they should GWmemetownOMEGALUL

pliant tusk
#

oh 100%

languid dagger
#

You can't override for and but you could use + instead. However is there a reason to since Foo would already be that new class with Base1 andBase2 in the mro

pliant tusk
#

see the reason is why not

paper echo
#

could use &

pliant tusk
#

see but now i really want to try and use and

spice pecan
#

& can work, and is not overloadable, it just returns one of the operands depending on their truth values, short-circuiting if the first one is False

#

Although I guess you could hack something together with some inspect magic

half wolf
#

You could let the first class trickle through, then go another pass by just reading the AST and redeclare the class as if and worked like that probably

#

Not sure where you'd hook that second pass in.

spice pecan
#

I guess you could put that in a decorator or a metaclass/parent class

#

So you'd hook in on __init_subclass__, for example, use some magic to get the declaration line and manually parse the parent list

wide shuttle
#

At that point, can you still modify the MRO?

#

My guess is that it's already read-only at that point

spice pecan
#

That's true

#

You could do something really dirty I guess

undone hare
#

The MRO isn't writable? lemon_thinking

#

I don't see why it would tbh

peak spoke
#

You can modify __bases__ at any point with a few hacks

wide shuttle
#

Also for a class that does not have other bases than object?

spice pecan
#
from inspect import getsource


class Base: pass
class OtherBase: pass


class A(Base and OtherBase):
    pass
        

text = getsource(A).split('\n')
text[0] = text[0].replace(' and ', ', ')
exec('\n'.join(text))

print(A.__mro__)

That's the dirtiest thing I've done in a while

#
PS C:\Users\FarmArt.DESKTOP\Desktop> py test.py
(<class '__main__.A'>, <class '__main__.Base'>, <class '__main__.OtherBase'>, <class 'object'>)```
undone hare
#

Wait, that is valid python code? lemon_thinking

#

What is the MRO if you keep the and?

peak spoke
#

It evaluates the bool values of the class values and returns the last evaluated as usual

undone hare
#

Oh right

boreal umbra
#

@peak spoke that happens for and?

#

!e print(2 and 3)

fallen slateBOT
#

@boreal umbra :white_check_mark: Your eval job has completed with return code 0.

3
boreal umbra
#

Omg

#

I feel like that's less useful or intuitive as or

spice pecan
#

They follow the same logic

boreal umbra
#

Right

spice pecan
#

Return the left operand if it's enough to determine the truthiness of the entire expression, else the right operand

#

For or, it's enough if the left one is True, but not enough if it's False

#

For and it's the other way round

boreal umbra
#

I figured

#

or has some handy uses though

spice pecan
#

People used that before the ternary became a thing iirc

#

condition and a or b

undone hare
#

I believe it is for optimization reasons at first, and then made into a feature, binary comparisons returns the last compared value

boreal umbra
#

I can't think of any obvious uses for this functionality of and

peak spoke
#

I've used it a few times

spice pecan
#

I don't think I've used that in serious code, but you can do some fun stuff with it

boreal umbra
#
def func(thing, a=None):
    a = a or []
    a.append(thing)
    return a
#

Not a perfect example

spice pecan
#

The chained comparisons are internally joined by and, so you can abuse that to hack in "custom" operators

grand crag
#

Not a perfect example
the thing is that you must compare the types, in addition to comparing the values

peak spoke
spice pecan
paper echo
hollow pewter
#

Is there any cmd in python to find biggest substring in alphabetical order.

#

Or do I need to search it through index?

visual shadow
hollow pewter
#

πŸ‘

spice pecan
#

Actually

#

I was toying around with metaclasses, and now I'm wondering if you can unpack a sequence into a class definition

#

Yes, yes you can

#
>>> class A: pass
...
>>> class B: pass
...
>>> class C: pass
...
>>> bases = A, B, C
>>> class Derived(*bases): pass
...
>>> Derived.__mro__
(<class '__main__.Derived'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)
plush root
#

how to start weather prediction, I mean use of numeric models (numerical methods)?

charred wind
#

hi, my name is Erik

#

nice to meet you all

steep turret
#

Heyy Guys! Im new here.. Nice to meet you guys

charred wind
#

hello, im new here as well

steep turret
#

Idk if here's the right place to ask that.. If its not, i'm sorry ...

Someone here worked with uwsgi?

I'm facing some issues here.. :(

Trying to deploy a project with multiple threads and Flask application. But I can't get it to work...

I want the threads that i'm creating only in main process (right now it is beeing replied on every process), and I want flask (and just flask) in multiple processes... Is this possible at all?

paper echo
steep turret
#

@charred wind hi there!

visual shadow
#

This room is reserved for discussions about the python language itself. See the room description for more info.

steep turret
#

Ohh

#

good.

#

Thank u guys

#

i'm gonna ask that there

boreal umbra
#

Or one of the off topic channels if you want to socialize.

charred wind
#

thanks!

heady mauve
#

imagine writing ray marching code and making a very crude console 3d graphics system

#

is there a way to modify text colors via RGB with the standard console on Windows 10?

grave jolt
#

@boreal umbra

def func(thing, a=None):
    a = a or []
    a.append(thing)
    return a

Well, actually, there's a bug --

x = 42
things = []
func(x, things)
print(things) # []
pliant tusk
#

Would need to be a if a is not None else []

peak spoke
#

is it a bug though? It returns the list that was appended to

final whale
#

would invert that condition to avoid having to use not

grave jolt
#

@peak spoke But it suddenly behaves differently when you provide an empty list.

normal field
#

@grave jolt what are you expecting things to be?

grave jolt
#

the function mutates a in all other cases, so it would make sense that it would mutate an empty list as well

normal field
#

So a test case like this would work?

x = 42
things = [24]
func(x, things)
print(things) # [24, 42]
cloud crypt
#

there’s a "bug" in the code

#

because it does not mutate anything that evaluates to False, not only None

visual shadow
#

Ah, exactly the feature I needed. lemon_pika

cloud crypt
#

good time to discuss deferred None-aware operators, huh?

#

πŸ‘€

normal field
#

To expand on @nekit's point, an empty list [] is False-y. So, a in your case would be assigned the second empty list which is a different object than an empty list passed in as a. Hence you're not mutating the initial empty list passed in.

cloud crypt
#
def append_thing(thing: T, some_list: Optional[List[T]] = None) -> List[T]:
    actual_list: List[T] = some_list ?? []
    actual_list.append(thing)
    return actual_list``` looks kinda neat
grave jolt
#

@normal field I know why it works like that. The problem is that it might not be the intention.

#

For example, if the second argument is reserved for some shared cache, it will not work properly when the cache is empty.

past otter
#

i wish i knew programming 😭

cloud crypt
#

We all went from the ground up, just keep up the hard work and don't give up! lemon_pleased

azure pewter
#

ajax

#

ajax

#

ajax ajax ajax

#

hmmm

unkempt rock
#

is this a JSON response ?

#

anyone know off the top of their head?

azure pewter
#

im not sure but i think no

edgy tulip
#
import module as md
obj1 = md
obj1.a =10```
so why do we not use parenthesis for instantiating through a module?
Given : the code in module is implemented such as to use @properties for functions
raven ridge
#

I don't understand the question. The only objects being instantiated there are a module object and an int, both of which don't need parentheses to instantiate because the language has special syntax for instantiating objects of those types (the import statement and integer literals, respectively)

pseudo cradle
#

Does Python have an exclusive OR operator that is not bitwise? If it doesn't... why not???

#

It doesn't seem to unless I'm missing something (which I may be)

flat gazelle
#

It is not all that common, and bool(a)^bool(b) is not horrible

pseudo cradle
#

I guess

stable grail
#

bool(a) != bool(b) maybe?

#

i do like lakmatiols version better though

#
def logical_xor(string_self, string_other):
    return bool(string_self) ^ bool(string_other)
#

@pseudo cradle

pseudo cradle
#

Yeah, both of those work

#

I just don't like them, haha

stable grail
#

if you want it to look more fancy then it is, take a look in the operator module

#

!d operator.xor

fallen slateBOT
#
operator.xor(a, b)``````py
operator.__xor__(a, b)```
Return the bitwise exclusive or of *a* and *b*.
stable grail
#

you have to do a bool() on a and b here as well

pseudo cradle
#

Yeah

stable grail
#

or implement your own __xor__

pseudo cradle
#

It just seems like it would be something fairly basic that I'm surprised isn't in the language. We have and and or after all, why not xor that behaves the same way?

stable grail
#

because edge cases are normally never a good enough reason to implement something into the standard library

#

!d numpy.logical_xor

fallen slateBOT
#
numpy.logical_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logical_xor'>```
Compute the truth value of x1 XOR x2, element-wise.

Parameters  **x1, x2**array\_likeLogical XOR is applied to the elements of *x1* and *x2*. If `x1.shape != x2.shape`, they must be broadcastable to a common shape (which becomes the shape of the output).

**out**ndarray, None, or tuple of ndarray and None, optionalA location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

**where**array\_like, optionalThis condition is broadcast over the input. At locations where the condition is True, the *out* array will be set to the ufunc result. Elsewhere, the *out* array will retain its original value. Note that if an uninitialized *out* array is created via the default `out=None`, locations within it where the condition is False will remain uninitialized.... [read more](https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_xor.html#numpy.logical_xor)
stable grail
#

there you go @pseudo cradle

#

its implemented in numpy

pseudo cradle
#

nice

stable grail
#

you could also implement your own version of this using lambda calculus

#

but that would be way overkill

boreal umbra
#

@grave jolt its not meant to be a great example, the point is just that if one wanted to have an optional argument that filters exactly any falsy object, that pattern would work.

swift imp
#

There's xor bc xor is another name for equivalence

#

A scalar xor is by definition ==

#

Scratch that

#

I'm thinking xnor which is equivalence

#

I mean look

#

a xor b == (a and not b) or (not a and b)

#

But on that note

#

~= is logically equivalent to xor

#

If the two things are not equal do this

#

So there's really no point

#

Bitwise xor is nice bc it's useful for sets and it's used for parity

gleaming rover
#

it's interesting because I just had a reason to use the equivalent yesterday

#

my values were already bool so I just used !=

grizzled marlin
#

Hi can someone help me with numpy

gleaming rover
grizzled marlin
#

Maybe

#

I was posting in general but I haven't had luck

gleaming rover
#

this is for discussion, not help.

grizzled marlin
#

tyty

#

mbmb

safe hedge
#

How does inheritance work with dataclasses?

#

Do you need both the base and subclass to be decorated?

brave badger
#

If you need to generate new methods for the subclass yes

safe hedge
#

Are you suggesting if the subclass only adds attributes then you wouldn't need to decorate it?

brave badger
#

You'd still need to decorate the subclass if you're adding __init__ attributes + generating dunder methods

safe hedge
#

Yeah I read that, I was just kind of intrigued by what happens if you make a subclass a dataclass but the parent wasn't

#

Like a mixin situation

#

I had this:

class CoerceIntMixin():
    def __post_init__(self):
        for field in dataclasses.fields(self):
            if field.type is int:
                curval = getattr(self, field.name)
                if curval is None:
                    continue
                setattr(self, field.name, int(curval))

And I was using it as the base of some dataclasses but then I realised I didn't make it a dataclass itself

#

And I couldn't work out if I was headed for some weird bugs

sacred vapor
#

I want to add L_0.5 loss in my model while training
i have written :: loss = tf.reduce_sum(tf.pow(tf.abs(self.Coef),0.5))
But its giving NaN Error!
How its working perfectly with L1 loss and L2 loss
loss = tf.reduce_sum(tf.square(self.Coef))
loss = tf.reduce_sum(tf.abs(self.Coef))
the above 2 lines are working perfectly, but i want to use L_0.5 loss....How to do that?

magic python
peak spoke
#

A class with abstract methods will raise when initialized because those methods should be overriden, the warning is probably there so the error is discovered even when your code doesn't take those paths during testing

magic python
#

i've not seen abstract methods before, have just heard the name

peak spoke
#

abcs allow you to create interfaces, if you subclass an abc you either get an error when trying to initialize it without the methods implemented or you get the whole interface the abc defines. For example python provides some in the collections.abc for common data structures in python https://docs.python.org/3/library/collections.abc.html

keen anchor
#

You have to write an efficient and pluggable API application. Describe how you would choose which framework to use and which framework you think would be best for the job and why.

#

My question is: What's a pluggable API in the first place?

mint forge
#

@keen anchor does this help:

REST service. Also, because the platform is pluggable, it means that you can expose any of your custom code as an API call or REST service as well. This means the days of difficult integration, and siloed functionality are over. Welcome to a RESTful development life!
fiery cloud
#

does they trying to say, writing handler for certain services?

mint forge
keen anchor
#

thanks

mint forge
#

np

proven dirge
#

Hi there, anyone has experience of pyinstaller?

vague mica
#

@proven dirge better to ask more specific questions. Someone having experiece with pyinstaller might not know what you are looking for.

unkempt rock
#
#include <iostream>
#include <stdio.h>

#define PVAR(x) printf("var" #x " + 1 = %d\n", var##x + 1) 

int main(void) {
    auto [var1, var2, var3] = (int[3]) {1, 2, 3};
    PVAR(1); PVAR(2); PVAR(3);
}
#

Is it possible to implement something like this in python?

#

Only thing that comes to my mind is ast but I've only used it once so I'm not so sure about it

half wolf
#

@unkempt rock the new debug feature in f strings?

unkempt rock
#

Ah..

#

Never knew that existed

paper echo
#

Is that the {x=} thing @half wolf ?

radiant fulcrum
#

What was the alternative people use over MyPy again?

#

dont get me wrong i love MyPy's system but holy fuck is it slow

cloud crypt
#

it is kinda stupid sometimes

#

because of static analysis and other things

#

pyre, pyright and pytype

paper echo
#

@radiant fulcrum pyre, pyright, pytype

#

pyre is by facebook, pyright is by microsoft, pytype is one of those "google but not actually google" projects

radiant fulcrum
pearl river
#

the spreadsheet view is just cProfile with easy sorting

#

but the graph is πŸ‘Œ

sacred tinsel
#

I look at the graph sometimes, it's nice

waxen kindle
#

Excuse me i have a question friends

#

I am Ozan i am studying master in data science and i enrolled dataquest datacamp udacity courses

#

what should i do as next after finishing

#

for the future issues , NLP , machine learning engineer like this

#

what are your suggestions thanks for everything . Best regards

gleaming rover
#

what should i do as next after finishing
@waxen kindle this is for discussion of the language; why not try #career-advice? you might get better help there

waxen kindle
#

Oh okey sorry about this someone in data science channel suggested that channel i enrolled as new

gleaming rover
#

Oh okey sorry about this someone in data science channel suggested that channel i enrolled as new
@waxen kindle yup we can talk in #data-science-and-ml, I pinged you

unkempt rock
#

anyone know how i can play audio from a URL without using vlc because im having problems with vlc. How can i play audio from an audio url without using vlc

boreal umbra
unkempt rock
#

okay

boreal umbra
#

is random.shuffle O(n)?

peak pollen
#

I believe so