Namespaces are one honking great idea

Ethan Furman ethan at stoneleaf.us
Sun Jul 3 01:14:37 EDT 2016


On 07/02/2016 08:44 PM, Steven D'Aprano wrote:

> Try getting this behaviour from within a class:
>
>
> class Food(metaclass=Namespace):
>
>      # (1) no special decorators required
>      def spam(n):
>          return ' '.join(['spam']*n)
>
>      # (2) can call functions from inside the namespace
>      breakfast = spam(5)
>
>      # (3) no "cls" or "self" argument
>      def lunch():
>          # (4) can access variables using their undotted name
>          return breakfast + ' and eggs'
>
>      def supper():
>          # (5) likewise functions (a special case of #4)
>          return lunch() + ' and a fried slice of spam'
>
>      def mutate(n):
>          # global inside the namespace refers to the namespace,
>          # not the surrounding module
>          global breakfast
>          breakfast = spam(5)

> Can you do all of that with an ordinary class?

You can get #2 already, but not the rest (without your spiffy code ;) :

Python 3.5.1+ (3.5:f840608f79da, Apr 14 2016, 12:29:06)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
 >>> class Huh:
...   def blah(text):
...     print('blah blah %s blah blah blah' % text)
...   blah('whatever')
...
blah blah whatever blah blah blah

--
~Ethan~



More information about the Python-list mailing list