r/Python • • Dec 22 '18

Xpost from Woodworking

Post image
1.1k Upvotes

84 comments sorted by

View all comments

0

u/[deleted] Dec 22 '18

[deleted]

7

u/nerdmor Dec 22 '18

from random import choice

16

u/artificialignorance Dec 22 '18 edited Dec 22 '18
print(__import__('random').choice([‘slice', 'chop', 'dice’]))

4

u/haliax69 Dec 22 '18

TIL I can import modules this way. Thanks!

6

u/Ph0X Dec 22 '18

Please don't. It's good to know, but almost never the right choice.

And if you need dynamic imports, use importlib instead.

1

u/haliax69 Dec 22 '18

Oh, I kinda figured that, but it's nice to use when running commands directly from the command line like:

python3 -c "print(__import__('datetime').datetime.now().strftime('%d, %b %Y'))"

3

u/Ph0X Dec 22 '18

Well on there you can use semicolon, that's still probably cleaner

python3 -c "import datetime; print(datetime.now().strftime('%d, %b %Y'))"

1

u/haliax69 Dec 22 '18

Learned something else today: semicolon = new line. Thanks man!

Just out of curiosity, is there something that replaces indentation?