Reputation: 2959
For test purposes I need to create something like an empty object with some particular fields. Let me clarify by example:
Currently there is a structure:
var = {
'blas': {
'bla': 0.250,
'bla1': 0.300,
'bla2': 6,
...
},
'somth1': self.smth1,
'something': [
{ 'h1': 66.00 },
{ 'h2': 47.00 },
{ 'h3': 85.00 },
{ 'h4': 32.00 },
{ 'h5': 34.00 }
],
'this_has_to_be_object'.field: 1
}
The thing I want is for 'this_has_to_be_object'
to be an actual object to which I can add some fields and set values. The objective of such behaviour is to test another function that operates with 'this_has_to_be_object'.field
.
Upvotes: 0
Views: 849
Reputation: 582
var = {
'blas': {
'bla': 0.250,
'bla1': 0.300,
'bla2': 6,
...
},
'somth1': self.smth1,
'something': [
{ 'h1': 66.00 },
{ 'h2': 47.00 },
{ 'h3': 85.00 },
{ 'h4': 32.00 },
{ 'h5': 34.00 }
],
'this_has_to_be_object':{'field': '1'}
}
this is already a object, if you said you want to add some field inside
you can do it like
...this_has_to_be_object.newField = 3;
isn't this what you want?
Upvotes: 1
Reputation: 9064
Why not use a Default dict here.e.g.
var = defaultdict(int)
var.update({
'blas': {
'bla': 0.250,
'bla1': 0.300,
'bla2': 6,
...
},
'somth1': self.smth1,
'something': [
{ 'h1': 66.00 },
{ 'h2': 47.00 },
{ 'h3': 85.00 },
{ 'h4': 32.00 },
{ 'h5': 34.00 }
],
'this_has_to_be_object'.field: 1
}
)
Now var['anything'] would always return with 0.
I guess that is the functionality you require for testing, Right ?
Upvotes: 1
Reputation: 31270
Namedtuples are on way, if they don't have to be mutable:
from collections import namedtuple
MyTupleType = namedtuple('MyTupleType', ['field'])
yourobject = MyTupleType(field=3)
print(yourobject.field) # prints 3
If it's for testing, then using the Mock library is also handy (see http://www.voidspace.org.uk/python/mock/ ; unittest.mock
is part of the standard library since Python 3.3 as well).
yourobject = MagicMock()
yourobject.field = 3
Note that yourobject now has any field or method you try to access on it, and their values are all yet another MagicMock instance. It's a very powerful unit testing tool.
Lastly you can just create a boring dummy class:
class Dummy(object):
pass
yourobject = Dummy()
yourobject.field = 3
Upvotes: 1