문제

I'm designing something similar to Admin.Autodiscover() of Django.

The first hurdle that I'm facing is getting the path of the file from which admin.autodiscover() is called, so that I can traverse the apps/libraries in that folder and figure out which models should be kept in admin.

How do I do that?

도움이 되었습니까?

해결책

The Zen of Python says: Explicit is better than implicit.

Why not call it like this: your.autodiscover(__file__), or even your.autodiscover(dirname(__file__)). That way, someone who reads your code doesn't have to look for the magic in your autodiscover function, or look it up in the documentation.

다른 팁

Using traceback.

Here's one way I found to do that:

import traceback
def get_caller_filename():
   # last element ([-1]) is me, the one before ([-2]) is my caller. The first element in caller's data is the filename
   return traceback.extract_stack()[-2][0]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top