Can a dictionary be used to pass variables to a function? [duplicate] - python

This question already has answers here:
Passing a dictionary to a function as keyword parameters
(4 answers)
Closed 5 years ago.
I have a class with an init function that needs ~20 variables passed to it. Instantiations of the class are rather ugly:
some_var = MyClass(param1=mydict('param1')
param2=mydict('param2')
param3=mydict('param3')
...
param20=mydict('param20')
I keep all of those parameters in a dictionary for easy handling already. Not all parameters are necessary so I don't want the class to accept only a dictionary object I don't think.
I'm wondering if I there's a nice trick to clean this up by specifying that the parameters to init are to be taken from the dictionary?
I'm just looking for tips and tricks on tidying this up a little. I have quite a few long/ugly instantiations of this class.

You can use keyword argument expansion:
some_var = MyClass(**mydict)

Related

Specify a list of strings as a function param types [duplicate]

This question already has answers here:
Type hinting a collection of a specified type
(5 answers)
Closed 2 years ago.
I'm trying to define a list of str as a type for a function param but I don't know how to do this
I know that python allows you to define functions specifying the type of value expected by the function params. Example:
def f(param: str):
print(type(param))
But I don't know is how is this annotation called param: str, therefore is pretty hard to find documentation on this. Also I understand that is only an aesthetic in code documentation and not some kind of type enforcement for the params.
Could you help me with a way to define a list of str and the name of this annotation?
For a more clear example of what I want in TypeScript it would be written this way
function func(param: string[]) {}
The typing module has List for this purpose
from typing import List
def f(param: List[str]):
pass

How to assign a variable inside a function with the variable as an input for the function? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 3 years ago.
def convert(target):
#Some code here
target = 20
convert(x)
print(x)
I expected the output to be 20, but there is always an error. "NameError: Name x is not defined" Is there some way that I could fix that?
It sounds like you are trying to pass the value by reference, which goes against the grain of Python, which passes variable by assignment. The easiest "solution" is to refactor your code so it returns the new value, as others have suggested.
In some languages (e.g. PHP), you can specify that certain arguments are to be passed by reference (e.g. by prefixing the variable name with a "&"), but in practice this often makes the code harder to read and debug.
For more information, see:
How do I pass a variable by reference?

Calling a method from a constructor in python [duplicate]

This question already has answers here:
Python function calling order
(5 answers)
Closed 3 years ago.
The initial question I had was whether or not a method could be called from a Python constructor. The answer here suggests that it can, but this surprised me some as, based on my reading, python cannot use something that hasn't been previously defined in the code. Looking at the answers in the linked thread, it seems like they are using a method in the constructor that is defined later in the text. How is this possible in python?
Thanks.
When you would be running the code the class would be created , the function wouldn't be called
The function would only be called by object in main function by that time the definition of function would be compiled and known.
Try this
Declare a class and then call a function which is not a member of class * and also not declared
And declare it later , it would throw an error

Why create an empty class, then instantiate it and set some attributes? [duplicate]

This question already has answers here:
Empty class object in Python
(4 answers)
Closed 7 years ago.
html2txt contains the following code:
class Storage: pass
options = Storage()
options.google_doc = False
options.ul_item_mark = '*'
I've not seen such an approach before. What's the benefit/use of this approach over setting up the attributes in __init__(), and is a class even necessary here?
Suppose you want to store some collection of named data. You could use a dict but you like the look of dotted attributes in a class object. Just create the most boring class possible and use python's native attribute assignment to do the trick. It is usually a question of aesthetics.
If you know the attributes ahead of time you can use namedtuples for this kind of functionality.
From the python docs:
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

The correct way to unpack keyword arguments (kwargs) [duplicate]

This question already has answers here:
Proper way to use **kwargs in Python
(14 answers)
Closed 8 years ago.
With keyword arguments, you can't just reference potential keyword values in the dict, since they may not be present. What's the best way to reference keyword values that may or may not be there? I find myself doing things like this:
def save_link(link, user, **kwargs):
if "auto" in kwargs:
auto = kwargs["auto"]
else:
auto = False
in order to provide default values and create a variable that is reliably present. Is there a better way?
You may use the get property of dict:
auto = kwargs.get('auto', False)
This allows for using a default value (Falsein this case).
However, please be quite careful with this approach, because this kind of code does not complain about wrong keyword arguments. Someone calls funct(1,2,auot=True) and everything looks ok. You might consider checking that the kwargs you receive belong to some certain list.

Categories