In py-automapper lib sourceCode, I find an method which use array to create instance, but i do not find an real parameter example. So can you help me to figure out it?
type(obj)
returns the class of obj
, and calling a class instantiates an instance of it.
In other words, the code creates an instance of the class of obj
with a list produced by the comprehension as the argument to the constructor.
I know the meanings, But I never use this method to create an instance.
class Address(BaseModel):
street: Optional[str]
number: Optional[int]
zip_code: Optional[int]
city: Optional[str]
address = Address(street="Main Street",number=1,zip_code=100001,city='Test City')
type(address)([......])
For this scenario, how should we define the stracture?
Can you use the demo class to help me to define an real parameter values?
To understand how to create an instance of type(obj)
, we would need to know what obj
it uses (so that we can find out what the type
result will be).
But from the context, we can see that only one argument will be passed, and that argument is a list.
You can’t do this with a BaseModel
(I assume you are using Pydantic), unless you add the ability yourself. The base class defined a different constructor, that works a different way.
When you say type(address)(...)
in your example, it has the same effect as Address(...)
. The point of using type
this way, is that it gives you the class back. So the ...
part has to follow the same rules.
Please do not feel like you need to understand the code in a library, in order to use the library. That is in fact the opposite of how it works. The entire reason to use a library is so that you don’t have to worry about making it work. Someone else already did it for you.