__file__ vs __FILE__

Matimus mccredie at gmail.com
Mon Nov 5 19:50:29 CET 2007


On Nov 5, 1:07 am, sandipm <sandip.m... at gmail.com> wrote:
> interestingly...
> I wanted to reuse this code so i wrote function in a file
>
> def getParentDir():
>     import os
>     return os.path.dirname(os.path.abspath(__file__))
>
> and called this function, in another file, its giving me parent
> directory of file where this function is defined.?

This is true. __file__ is defined at the module level where the
function is defined.
> how to reuse this piece of code then? or am i doing something wrong?
>

You have a few choices. You could implement it wherever you need it
which might actually be nice from a OO point of view. You could modify
the function above to accept a parameter and operate on the __file__
attribute of that parameter. Or, you could use the inspect module to
look at the stack and operate on the __file__ attribute of the caller.

The first one is obvious to implement, although it will only apply to
modules you have implemented. The second one I think someone has
already posted a solution to. Here is how to implement the third one
(this is also usable with a parameter).

[code]
import inspect
import os

def getpardir(obj=None):
    if obj is None:
        obj = inspect.stack()[1][0]
    return os.path.dirname(inspect.getfile(obj))
[/code]

Some may choose to stay away from this sort of thing though, since
inspecting the stack can tend to feel a bit like voo-doo. Passing a
parameter is probably your best bet IMHO.

Matt




More information about the Python-list mailing list