[Python-ideas] Add __main__ for uuid, random and urandom

Koos Zevenhoven k7hoven at gmail.com
Sun Apr 17 15:28:58 EDT 2016


On Sat, Apr 2, 2016 at 11:22 AM, Random832 <random832 at fastmail.com> wrote:
> On Sat, Apr 2, 2016, at 02:37, Koos Zevenhoven wrote:
>>  python -e "random.randint(0,10)"
>>
>> which would automatically import stdlib if their names appear in the
>> expression.
>
> #!/usr/bin/env python3
> import sys
> class magicdict(dict):
>     def __getitem__(self, x):
>         try:
>             return super().__getitem__(x)
>         except KeyError:
>             try:
>                 mod = __import__(x)
>                 self[x] = mod
>                 return mod
>             except ImportError:
>                 raise KeyError
>
> g = magicdict()
> for arg in sys.argv[1:]:
>     try:
>         p, obj = True, eval(arg, g)
>     except SyntaxError:
>         p = False
>         exec(arg, g)
>     if p:
>         sys.displayhook(obj)
>
>
> Handling modules inside packages is left as an exercise for the reader.

Thanks :).

There were some positive reactions to this in the discussions two
weeks ago, so I decided to go on and implement this further. Then I
kind of forgot about it, but now the other getattr thread reminded me
of this, so I came back to it. The implementation now requires Python
3.5+, but I could also do it the same way as I did in my 'np' package
[1], which in the newest version (released three weeks ago), uses
different module-magic-method approaches for Python<3.5 and >= 3.5, so
it even works on Python 2.

So here's oneline.py:

https://gist.github.com/k7hoven/21c5532ce19b306b08bb4e82cfe5a609

I suppose this could be on pypi, and one could do things like

    oneline.py "random.randint(0,10)"

or

    python -m oneline "random.randint(0,10)"

Any thoughts?

-Koos

[1] https://pypi.python.org/pypi/np


More information about the Python-ideas mailing list