Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python generic Container?

Tags:

python

It can someone be convenient to group variables under a given object.

My use case is tensorflow, where you often have to define a graph first and then feed it with actual data. To avoid getting the names of the graph variables jumbled up with those of the data variables, it's useful to group them all under an object. What I've been doing is:

g = lambda: None
g.iterator = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(minibatch_size).make_initializable_iterator()
g.x_next, g.y_next = g.iterator.get_next()
g.data_updates = g.x_data.assign(g.x_next), g.y_data.assign(g.y_next)

Except that when you use lambda: None your coworkers tend to get angry and confused.

Is there an alternative that provides equally clean syntax but uses something that is more obviously a container than lambda: None?

I first tried making them all static members of a class, but the problem is that static members cannot reference other static members. g=object() would be nice but doesn't allow you to assign attributes.

like image 501
Peter Avatar asked Aug 27 '26 05:08

Peter


1 Answers

If it's not worth defining a dedicated class, you can use types.SimpleNamespace, which is a class specifically designed to do nothing but hold attributes.

g = types.SimpleNamespace()
g.iterator = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(minibatch_size).make_initializable_iterator()
g.x_next, g.y_next = g.iterator.get_next()
g.data_updates = g.x_data.assign(g.x_next), g.y_data.assign(g.y_next)
like image 54
Aran-Fey Avatar answered Aug 28 '26 20:08

Aran-Fey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!