On Jan 5, 1:12 pm, Nav <navjotmu...@gmail.com> wrote: > When we create instances of objects by doing > x = className () > are we using globalnamespace?
Well, you're using a namespace, which namespaces its in would depend on the scope in which that assignment occurred. And there's not really a global namespace, only module ones. > if yes then: > if using globalnamespace is bad then why does every book or tutorial > about python classes give the above style of assignment as an > example? That's a basic assignment example. It's not a direct manipulation of globals(), like the solution given by Jan, which you seem to feel is the answer. And unless it happens outside of a nested scope like a class or function definition, it's not 'global'. > Second why do we use a dictionary to create something like this? I > know how it works, but what is wrong with simply creating instances > automatically? If I came across code like this in a joint project I was working on: def somefunc(*someparams): magical_instance_injection() for elem in magically_appearing_collection: .... We'd have serious words about the readability & maintainability of such code. If the values are important, make a clear set up that places them in a mapped collection, and make it obvious that the collection is how those values are used. Also, you've removed the set up from the place where the values are actually used, meaning I'd have to look at two sets of code to identify the values' names, as well as to confirm that 'some_random_label' _is_ actually one of the instances and not just a value you're using without instantiating. > Once created the data for the instances is > automatically saved in their own space? Why have a round about way > using dictionaries? Because using a dictionary removes the dependency your function has on the injection code, which in turns makes it more flexible for re-use. Let's assume you write your injection function, and call it within every function that uses those objects: def inject_values(): # here be global() manipulations def do_that_thang(): inject_values() ... What if you want to do_that_thang to a separate set of values? With this approach, you'd have to extend like so: def inject_values2(): ... def do_that_thang2(): inject_values2() ... You could, of course, have one inject_values function that accepts a flag and returns the appropriate set of values, but now you're having to modify that function every time the values change. With a dictionary, it's just so much simpler: values1 = dict( a = SomeObject(1), b = AnotherObject(1)... ) values2 = dict( a = SomeObject(2), b = AnotherObject(2)... ) def do_that_thang(values): c = values['a'].thanger(values['b']) ... It's clean, readable and far more easily extensible. It's also far more obvious what you're doing, which you'll really appreciate when you return to the code in a year's time :) -- http://mail.python.org/mailman/listinfo/python-list