RE: Configuring an object via a dictionary

Liste des GroupesRevenir à cl python 
Sujet : RE: Configuring an object via a dictionary
De : <avi.e.gross (at) *nospam* gmail.com>
Groupes : comp.lang.python
Date : 17. Mar 2024, 23:26:51
Autres entêtes
Message-ID : <mailman.115.1710710819.3452.python-list@python.org>
References : 1 2 3 4 5 6
User-Agent : Microsoft Outlook 16.0
If we are bringing up other languages, let's return to what was part of the original question.

How van a dictionary be used in python if your goal is to sort of use it to instantiate it into a set of variables and values inside the local or global or other namespaces? Can we learn anything from other programming languages with other paradigms?

I was thinking that in one sense, python has other kinds of collections such as a class or class member with internal variables that also has some features similar enough.

 I mean if I were to call a function with one argument being a dictionary like {"a":1, "c": 3} where in theory any number of similar key value pairs might exist or not be present, then the question sounded like a request to create variables, in this case a, and c, that hold those values. I will not debate the wisdom of doing that, of course. Nor will I debate what should happen if some of those variable names are already in use. OK?

There are ways to do this albeit some are a tad obscure such as taking a printable representation of the dictionary and editing it and feeding that to an eval.

But could you serve a similar purpose by passing an object containing varying internal fields (or methods) and values including some of the dataclasses Dave Neal is highlighting? Is there some overlap with using dictionaries?

In Javascript, I would say they have a very different view in which all kinds of things overlap and their objects can even implement what others might call arrays albeit a tad weirder like allowing missing indices and ignoring non-numeric indices for some purposes. Someone may wish to chime in if people can and do take such objects passed in and split them into individual variables as requested.

What I wanted to mention is some philosophical issues in the R language in which the default language used other data structures to loosely support what dictionaries often do in python. They have named lists where components optionally can have a name as in list(a=5, "b"=6, 7, "hello world") and they have data structures called environments. Loosely, an environment is a set of name=value pairs and is pretty much like a dictionary and is mostly used behind the scenes as the interpreter searches for variable names in a sequence of environments such as the parent environment. But you can use environments all over the place on purpose and as noted, a named list simulates an environment.

So a fairly common usage when using base R is to take a data.frame (which is at first approximation a list of named vectors all the same length) and want to work with the column names without extra typing. If I had a data.frame that looked like mydf <- data.frame(a=1:3, b=3:1) then if I wanted to add corresponding entries, I might type:

result <- mydf$a + mydf$b

inside a with statement, an environment is put on the stack consisting of the contents of mydf and you can now use things like:

result <- with(mydf, a+b)

There is more but the point is for those who hate the extra typing of long names, this can be useful and a tad dangerous if the variable names are not unique.

But as R delays evaluation in various ways, a similar style has evolved in an assortment of packages to the point where I often program in a style that looks like:

result <-
  mydf |>
  mutate(newcol = a+b, doubled = 2*newcol, ...)

The point is that all kinds of things that seem like local variables can be used as if they had been declared withing some environment but that are not available once you leave that region.

So perhaps there is some validity in a request to be able to just pass an argument as a dictionary in python and have it unpacked.

In actuality, I wonder if the OP is aware of the unpacking functionality you can get using **dict in a function invocation.

Say you have a function that expects any combination of three variables called the unoriginal names of alpha/beta/gamma and you want to call it with a dictionary that contains any subset of those same keys and nothing else:

mydict = {"alpha":5, "beta":6}

def unpacked(alpha=None, beta=None, gamma=None):
  print(alpha if alpha != None else "No alpha")
  print(beta if beta != None else "No beta")
  print(gamma if gamma != None else "No gamma")

  If I now call unpacked with ** mydict:

unpacked(**mydict)
5
6
No gamma

Within the body of that function, arguably, I can tell if something was passed or not, assuming None or any other sentinel I choose is not used except in setting the default.

And if you add other unknown names, like delta, they seem to be ignored without harmful effects or can be caught in other ways.

unpacked({"gamma":7, "delta":8})
{'gamma': 7, 'delta': 8}
No beta
No gamma

So given a function similar to this, and you wanting LOCAL variables set, how would this do if you wanted these three or any number, and in a row:

mydict = {"beta":6, "alpha":5}

def dict_to_vars(alpha=None, beta=None, gamma=None):
  return(alpha, beta, gamma)

alpha, beta, gamma = dict_to_vars(**mydict)

The result works no matter what order you have added to the dictionary as long as you know exactly which N you want. Obviously, you may not be thrilled with None as a value and can add code to remove empty variables after they have been instantiated.

alpha
5
beta
6
gamma
>

If you want to ignore some entries, use _ in your list of places for items you want to toss.

alpha, _, _ = dict_to_vars(**mydict)

The above is really just keeping alpha.

Of course if the possible keys are not known in advance, this does not work but other languages that allow this may be better for your purpose.



-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Peter J. Holzer via Python-list
Sent: Sunday, March 17, 2024 11:12 AM
To: python-list@python.org
Subject: Re: Configuring an object via a dictionary

On 2024-03-17 17:15:32 +1300, dn via Python-list wrote:
On 17/03/24 12:06, Peter J. Holzer via Python-list wrote:
On 2024-03-16 08:15:19 +0000, Barry via Python-list wrote:
On 15 Mar 2024, at 19:51, Thomas Passin via Python-list <python-list@python.org> wrote:
I've always like writing using the "or" form and have never gotten bit
 
I, on the other hand, had to fix a production problem that using “or” introducted.
I avoid this idiom because it fails on falsy values.
 
Perl has a // operator (pronounced "err"), which works like || (or),
except that it tests whether the left side is defined (not None in
Python terms) instead of truthy. This still isn't bulletproof but I've
found it very handy.
 
 
So, if starting from:
 
    def method( self, name=None, ):
 
 rather than:
 
    self.name = name if name else default_value
 
ie
 
    self.name = name if name is True else default_value

These two lines don't have the same meaning (for the reason you outlined
below). The second line is also not very useful.



the more precise:
 
    self.name = name if name is not None or default_value
 
or:
 
    self.name = default_value if name is None or name

Those are syntax errors. I think you meant to write "else" instead of
"or".

Yes, exactly. That's the semantic of Perl's // operator.

JavaScript has a ?? operator with similar semantics (slightly
complicated by the fact that JavaScript has two "nullish" values).

        hp

--
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp@hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"


Date Sujet#  Auteur
17 Mar 24 o Re: Configuring an object via a dictionary1<avi.e.gross

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal