Python assign dictionary value in a constructor [duplicate] - python

This question already has answers here:
Why does adding a trailing comma after an expression create a tuple?
(6 answers)
Closed 2 years ago.
Please look at the below code.
signal = {
"id": "p752",
}
class Trigger:
def __init__(self, signal):
self.id = signal['id'],
print(type(signal['id']))
print(type(self.id))
def get_trigger(self):
print(self.id)
t1 = Trigger(signal)
t1.get_trigger()
The output I get is
<class 'str'>
<class 'tuple'>
('p752',)
I honestly don't know what is happening here. When I assign signal['id'] to 'id' inside the constructor why is changing to a tuple?

self.id = signal['id']
Trailing comma is to be removed so it is treated as a tuple

Related

Access subtype of type hint [duplicate]

This question already has answers here:
How to access the type arguments of typing.Generic?
(5 answers)
Closed 19 days ago.
class MyClass:
prop: list[str]
MyClass.__annotations__
# {'prop': list[str]}
How do I access "str"?
As a more generic question, given an obnoxiously complex and long type hint, like prop: list[set[list[list[str] | set[int]]]], how do I access the internal values programmatically?
Here is a function that will recursively pretty print the type and all the types inside it, using typing.get_args as suggested by #user2357112 :
from typing import List, Set, Union
import typing
complex_type = Union[List[str], Set[int]]
def log_type_layers(typing_type, indent=4, depth=0):
current_type = typing_type
print(" "*indent*depth + str(current_type))
for subtype in typing.get_args(current_type):
log_type_layers(subtype, indent=indent, depth=depth+1)
log_type_layers(complex_type)
Output:
typing.Union[typing.List[str], typing.Set[int]]
typing.List[str]
<class 'str'>
typing.Set[int]
<class 'int'>

class __init__ takes parameters but turns them into tuples for some reason [duplicate]

This question already has answers here:
Why does adding a trailing comma after an expression create a tuple?
(6 answers)
Closed 6 years ago.
I have a very simple class:
class Item(object):
def __init__(self, guid, sku, name):
self.guid = guid,
self.sku = sku,
self.name = name
When I create an object, such as:
item1 = Item('abc123', 1, 'abc1')
And I do:
print item1.guid
I get this as an output:
('abc123',)
Instead of the expected:
'abc123'
Any idea why it does this?
P.S.: name works as expected!
self.guid = guid, # Comma means create a tuple!
self.sku = sku,
self.name = name
You have done this yourself in your __init__ code. The tuple is constructed by a comma. Parentheses are just there to avoid ambiguity in some cases.
The correct code looks like this:
self.guid = guid
self.sku = sku
self.name = name
Python isn't doing it, you are, right here:
self.guid = guid,
self.sku = sku,
Notice those trailing commas? In python, the , is actually what constructs tuples. So guid, is saying "make a tuple of size one with guid as the element". Remove the trailing commas and you're good to go.
Unfortunately the , operator is also the argument separator in function calls and inline initialization of lists/dicts, so typically you encounter "tuple construction" as (a,b). But the () are only there to let the interpreter disambiguate between the , tuple construction operator and the , argument delimiter. If you're not in a case where there is such ambiguity, like an assignment, the , operator is all you need, even if nothing comes after it.

Returning individual string representation of all objects in list of objects [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 7 months ago.
Is it possible to return the string representation (using __str__) of all objects in a list of objects from a different classes own __str__ function?
Say I have a class that contains all methods being performed on Bar objects. Call this class Foo. Then:
class Foo:
def __init__(self):
self.bars = [] # contains Bar objects
def __str__(self):
return "This is the Foo object"
class Bar:
def __init__(self, arg1):
self.arg1 = arg1
def __str__(self):
return "This is Bar object: " + arg1
def main():
foo = Foo()
print(str(foo))
I want to print the string representation of all of the objects in self.bars WHEN I call main(), since creating an instance of the Bar object would not give me access to the string representation of all of the objects in self.bars.
To clarify, I am not asking the same question as in this post relating to the need of __repr__. Instead, I want to return each object's string representation individually, as with a for loop.
Is there anyway to do this, reasonably or unreasonably?
You already said how to do this, use a for loop.
return "".join([str(x) + "\n" for x in self.bars])

Could you help me with this simple kwarg example in python? [duplicate]

This question already has answers here:
What is the purpose and use of **kwargs? [duplicate]
(13 answers)
Closed 7 years ago.
I'm testing to use kwargs and have a trouble.
This is the python3 code :
class B:
def __init__(self, **kwargs):
print(kwargs['city'])
a = {'phone':'0101', 'city':'Daejeon'}
b = B(a)
But, there is an error like below :
b = B(a)
TypeError: __init__() takes 1 positional argument but 2 were given
Is there something wrong in my code?
I think that I just exactly follow the tutorial....
Keyword arguments are not passed that way.
obj1 = B(phone='0101', city='Daejeon')
obj2 = B(**a)

Python enum implementation [duplicate]

This question already has answers here:
How can I represent an 'Enum' in Python?
(43 answers)
Closed 8 years ago.
I have declared the enum as follows in python.I don't know how to use them.When I create an instance of this class it gives error as two arguments are required one given.
class CBarReference(Enum):
ThisBar = 0,
NextBar = 1,
Undefined=2
a=CBarReference()
I know what error is but I don't know what to give as the second argument other than self.
You should never have to create an instance of an enum; they're all accessed directly from the class, and you can just assign them to variables as you like:
a = CBarReference.ThisBar
b = CBarReference.NextBar
c = CBarReference.Undefined
d = CBarReference.ThisBar
assert(a == d)
assert(b != a)
assert(b != c)

Categories

Resources