tags:

views:

31

answers:

2

Suppose you have the following:

$ more a.py
import os

class A(object):
    def getfile(self):
        return os.path.abspath(__file__)

-

$ more b.py
import a

class B(a.A):
    pass

-

>>> import b
>>> x=b.B()
>>> x.getfile()
'/Users/sbo/tmp/file/a.py'

This is clear. No surprise from this code. Suppose however that I want x.getfile() to return the path of b.py without having to define another copy of getfile() under class B.

I did this

import os
import inspect

class A(object):
    def getfile(self):
        return os.path.abspath(inspect.getfile(self.__class__))

I was wondering if there's another strategy (and in any case, I want to write it here so it can be useful for others) or potential issues with the solution I present.

CW as it's more a discussion question, or a yes/no kind of question

+2  A: 
sys.modules[self.__class__.__module__].__file__
Ignacio Vazquez-Abrams
I like this, but one thing to note is that you will be given the byte compiled module.
lewisblackfan
I don't. I think it's *awful*. It's a bad method, and anyone that uses it is a bad person.
Ignacio Vazquez-Abrams
and headbutt kittens ? :D
Stefano Borini
A: 

i know this might be bad coding practice. include a by execfile() it.

Dyno Fu