Correct idiom for determining path when frozen in 3.4

Ben Finney ben+python at
Mon Mar 17 10:02:15 CET 2014

Mark Summerfield <list at> writes:

> What is the correct idiom for getting the path to a top-level module

I'm not sure I understand what this concept is. What do you mean by
“top-level module”?

> in 3.3 and 3.4 when the module might be frozen?
> At the moment I'm using this:
>     if getattr(sys, "frozen", False):
>         path = os.path.dirname(sys.executable)
>     else:
>         path = os.path.dirname(__file__)

That looks okay. Does it work?

The code is readable and Pythonic as is. But I would suggest several

    if getattr(sys, "frozen"):    # ‘getattr’ will return None by default

Also, why test for “sys.frozen” when you're about to use

    if getattr(sys, "executable"):

Lastly, it's slightly more Pythonic to execute the normal path
unconditionally, and let it raise an exception if there's a problem::

        executable = sys.executable
    except AttributeError:
        executable = __file__
    path = os.path.dirname(executable)

 \     “It is far better to grasp the universe as it really is than to |
  `\    persist in delusion, however satisfying and reassuring.” —Carl |
_o__)                                                            Sagan |
Ben Finney

More information about the Python-list mailing list