[Python-ideas] Add a feature similar to C++ "using some_namespace"
Masklinn
masklinn at masklinn.net
Mon Feb 7 21:36:16 CET 2011
On 2011-02-07, at 20:43 , Manuel Bärenz wrote:
> In C++, the the approach to the namespace problem is having different namespaces that should not contain different definitions of the same name.
> Members of a namespace can be accessed explicitly by e.g. calling "std::cout<< etc." or "using namespace std; cout<< etc."
>
> I understand Pythons approach to be "objects can be used as namespaces and their attributes are the names they contain". I find this a very beautiful way of solving the issue, but it has a downside, in my opinion, because it lacks the "using" directive from C++.
>
> If the object is a module, we can of course do "from mymodule import spam, eggs".
Or `from mymodule import *` though that's not exactly recommended.
On the other hand, since when can `using` be used on anything but a C++ namespace (which as far as I know is a well-defined entity, not an arbitrary object, and quite similar to a Python module though not identical)?
> But if it is not a module, this does not work.
>
> Consider for example:
>
> class Spam(object):
> def frobnicate(self):
> self.eggs = self.buy_eggs()
> self.scrambled = self.scramble(self.eggs)
> return self.scrambled> 42
>
> This could be easier to implement and read if we had something like:
>
> class Spam(object):
> def frobnicate(self):
> using self:
> eggs = buy_eggs()
> scrambled = scramble(eggs)
> return scrambled> 42
>
> Of course this opens a lot of conceptual questions like how should this using block behave if self doesn't have an attribute called "eggs", but I think it is worth considering.
My 2 cents: Javascript has this "feature" (with). It's utterly terrible, and mainly a very good way to shoot yourself in the foot repeatedly.
I especially find the assertion that:
> This could be easier to […] read
Extremely debatable: in my experience of that feature in Javascript, it makes code much harder to understand and reason about.
More information about the Python-ideas
mailing list