Avoiding if name == main - James Abel

preview_player
Показать описание

Sponsor Acknowledgement

#pybay #pybay2019 #python #python3
Рекомендации по теме
Комментарии
Автор

That's the most convoluted way to avoid a tough conversation ever devised.

eonraider
Автор

Downloading external library to run hello world...

ChristianBrugger
Автор

Uggghh. Ugly non-pythonic module name for starters, call it something whimsical, like: `mainmain.py` or `genesis.py`
Then get rid of that ugly call from inspect, and use a decorator instead (what could possibly go wrong?):
`genesis.py`
def runme(mymain):
mymain()
return

your test script
from genesis import runme
@runme
def main():
print("Hello Maine!")

This is way cooler. Hell, I'm not even a python expert, why did Mr Abel have to do it the hard way? You can even put @runme on any other function and it'll also be run like your main(). If you wish to restrict such profligacy then just put a blocker in runme() so that it will only run a mymain with the __name__ of "main" if you want to spoil the fun, so to be an ass:

# `genesis.py`
def runmain(umain):
if umain.__name__ == 'main':
umain()
return

Then your script would use:

from genesis import runmain
@runmain
def main():
print("Hello Maine!")

and any other decorated function will not run now. If a real pythonista can tell mus why using a decorator like this is bad, please do drop a reply comment.

Achrononmaster