2

I have a main class and inherited class. I have a decorator function in main class. This following code in base.py.

def functionErrorCase(functionParam): def wrapper(self): try: functionParam(self) except Exception as e: self.InsertError(os.path.basename(__file__), functionParam.__name__) return wrapper 

Used in all functions in inherited class "__ file __" Command return base.py file name but i want the filename of the used class

How to return the used class file name ?

1
  • Are you aware of the .__module__ attribute, the inspect and traceback module?? Commented Feb 23, 2020 at 20:33

1 Answer 1

5

The global variable __file__ is always going to have the filename of the module you read it in. If your code is in base.py, that's the file name it's going to find. To read the file from another module, you'll need to read __file__ from its globals. Conveniently, you can access the globals of a function through its __globals__ attribute. So you could try functionParam.__globals__['__file__'].

But there may be an even better option that doesn't require using __file__ at all. Python functions have a __module__ attribute that names the module that they're defined in. If you don't need the .py at the end of the file name, that might be more useful than __file__. You might also consider using the __qualname__ of the function instead of the regular __name__, since the former will include the name of any class the function is declared in (e.g. "Foo.bar" for the bar method of the Foo class).

Sign up to request clarification or add additional context in comments.

4 Comments

Note that __qualname__ does not include the module name, only the path inside the module. The __module__ holds the module name.
@MisterMiyagi: Thanks for the correction. I've edited my answer to state things correctly. __qualname__ is still valuable, but in this context you're entirely right that __module__ is more what the questioner wants.
FWIW, I think functionParam.__globals__['__file__'] is what the OP wants.
Thank you Blckknght for answer the question. i writed functionParam.__globals__['__ file __'] command then is worked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.