Wednesday, November 29, 2017

a __main__ by any other __name__

$ cat <<EOF > what_is_happening.py
if __name__ == "__main__":
    import what_is_happening
else:
    print("what is happening?")
EOF

$ python what_is_happening.py
what is happening?


Ambiguous entrypoints can create a maze of state in your program.  In case the above example doesn't seem so bad, lets make it worse.


$ cat <<EOF > innocent_bystander.py
import what_is_happening

def func(): raise what_is_happening.TrustFall('catch me!')
EOF
 

$ cat <<EOF > what_is_happening.py
import innocent_bystander

class TrustFall(Exception): pass

if __name__ == "__main__":
    try:
        innocent_bystander.func()
    except TrustFall:
        print("gotcha!")
    except Exception as e:
        print('oops, butterfingers!')
        print('{} is not {}.... what have I done?'.format(
            type(e), TrustFall))
EOF

$ python what_is_happening.py
oops, butterfingers!
<class 'what_is_happening.TrustFall'> is not <class '__main__.TrustFall'>.... what have I done?


What happened?  This is executing the main module twice, a special case of double import.

One solution is to put import guards in all entrypoint scripts:
if __name__ != "__main__":
    raise ImportError('double import of __main__')






4 comments:

  1. leather jackets is needed now a days so here is the leather jacket website Instyle jackets where you are having all kind of leather jackets.

    ReplyDelete
  2. I am an experienced writer working as an academic writer at write my custom essay for seven years provides their assignment writing service to students globally.

    ReplyDelete
  3. we have been predominately serving residential clients throughout Fence installers Edmonton and its surrounding areas. Our mission to provide each and every customer with the best possible fence and the highest level of customer service. We understand how important security is to you, and that is why we have honed our technique for over 20 years to create a perfect fence no matter the project

    ReplyDelete
  4. Our focus is on providing external floating roof tankservices, site survey and studies advice operating under the best available technology, highest quality and most reliable equipment and design solutions available on the market.

    ReplyDelete