I want to create an extension method for objects that check to see if the object is null and throw an exception if it is. I want to keep the original variable name though. Can I somehow get it from within the extension method? It is "cumbersome" to have to write customer.NotNull("customer")
vs customer.NotNull()
.
The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .
Method 3: Get Function Name in Python using __qualname__ attribute. The __qualname__ gives more complete information than __name__ and therefore can be more helpful in debugging. To extract the name from any object or class, you can also use its __qualname__ attribute.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
String To Function Using The eval() Function In Python We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ' () ' separated by the addition symbol ' + '.
No, unfortunately you can't. Variable names are not part available at run time. However, you can use expressions like this:
void NotNull<T>(Expression<Func<T>> expression)
{
var me = expression.Body as MemberExpression;
var name = me.Member.Name;
var value = expression.Compile().Invoke();
...
}
NotNull(() => customer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With