[Python-ideas] A "within" keyword
Robert Vanden Eynde
robertve92 at gmail.com
Sat Jun 9 05:11:16 EDT 2018
Classes Provide already some features of a namespace :
class cool_namespace:
A = 8
@staticmethod
def f():
return "yo"
@staticmethod
def g():
return (1 + cool_namespace.A) * cool_namespace.f()
And if you're tired of writing @staticmethod, you can write a class
decorator "namespace" :
@namespace
class cool_namespace:
A = 8
def f():
return "yo"
def g():
return (1 + cool_namespace.A) * cool_namespace.f()
And I think this decorator already exists somewhere.
Le sam. 9 juin 2018 à 10:21, Steven D'Aprano <steve at pearwood.info> a écrit :
> On Fri, Jun 08, 2018 at 03:07:28PM -0700, Michael Selik wrote:
>
> > You can use ``eval`` to run an expression, swapping in a different
> globals
> > and/or locals namespace. Will this serve your purpose?
> >
> > In [1]: import types
> > In [2]: ns = types.SimpleNamespace(a=1)
> > In [3]: eval('a', ns.__dict__)
> > Out[3]: 1
>
> The public API for getting an object namespace is vars(ns).
>
> But why would we write eval('a', vars(ns)) instead of getattr(ns, 'a')
> or even better just ns.a? Is your Python code too fast and you need to
> slow it down? *wink*
>
> eval and exec are useful when the code you want to run needs to be
> constructed at runtime. Its not generally useful when you know what you
> want ahead of time as in your example above.
>
>
>
> --
> Steve
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180609/032a58f0/attachment.html>
More information about the Python-ideas
mailing list