0

I am trying to write a one liner, but it requires the random library.

import random
print(random.choice(["Red team","Blue team"]))

is there any correct syntax that could say something like

print(__import__(random).choice(["Red team","Blue team"]))

or

with open('random') as r: print(r.choice(["Red team","Blue team"])))
apinostomberry
  • 139
  • 1
  • 11
  • 4
    While one-liners are useful, one has to keep the Zen in mind and the code must also be *easily understood*; which (in my opinion) this concept is not. From that standpoint, I’d willingly go on a limb and say “No, there is not a *correct* syntax to accomplish this”. Stick with the standard import convention. – S3DEV Dec 02 '21 at 17:03
  • While I agree that readability is important and this should be avoided in virtually all situations, if you _really_ want to you can [use a semi-colon to separate statements](https://stackoverflow.com/a/59122264/354577): `import random; print(random.choice(["Red team", "Blue team"]))`. (Note that there are no line breaks there. Any that you see are an artifact of SO's comment rendering.) `random` remains imported afterwards, though. This isn't like a context manager. – ChrisGPT was on strike Dec 02 '21 at 18:55
  • Thank you!!!!!! I agree with the readability arguments. I didnt realize you can do this. I am not setting a pattern here, just sending a one line snippet people can use in an interpreter as a utility that has little to do with our mainstream product – apinostomberry Dec 03 '21 at 14:07

1 Answers1

-1

Even though it is discouraged, importlib.import_module is the function you're looking for.

import importlib
importlib.import_module("random").choice(["Red team","Blue team"])
vincenzoo
  • 9
  • 2
  • I don't think this is what OP is asking for – ChrisGPT was on strike Dec 02 '21 at 17:10
  • 3
    So, instead of `import random`, you suggest `import importlib` in order to use it and import random? – buran Dec 02 '21 at 17:20
  • I agree with @Chris. If importlib were part of standard python this would be exactly what I want, so its not technically wrong but unfortunately this robs peter to pay paul because you have to add the import statement to get impportlib making it still two lines – apinostomberry Dec 02 '21 at 18:29