Determine function name from within that function
import inspect def foo(): print(inspect.stack()[0][3]) print(inspect.stack()[1][3]) # will give the caller of foos name, if something called foo foo() output: foo <module_caller_of_foo>
import inspect def foo(): print(inspect.stack()[0][3]) print(inspect.stack()[1][3]) # will give the caller of foos name, if something called foo foo() output: foo <module_caller_of_foo>
Referencing ECMA-335, the is operator generates the isinst object model IL instruction (Partition III §4.6), which is part of the base instruction set as opposed to being part of the Reflection library (Partition IV §5.5). Edit: The is operator is extremely efficient compared to the reflection library. You could perform basically the same test much … Read more
Here is an implementation of a locals() function. It will return a table of locals from the calling scope: function locals() local variables = {} local idx = 1 while true do local ln, lv = debug.getlocal(2, idx) if ln ~= nil then variables[ln] = lv else break end idx = 1 + idx end … Read more
Is there a way to print out a complete list of available members of a type or instance in Rust? Currently, there is no such built-in API that you can get the fields at runtime. However you can retrieve fields by using two different ways. Declarative Macros Procedural Macros Solution By Using Declarative Macro macro_rules! … Read more
No, there is no way to do it in Python code with this signature — if you need this information, you need to change the function’s signature. If you look at the Python C API, you’ll see that the actual way arguments are passed to a normal Python function is always as a tuple plus … Read more
You can return any types’ name by using string interpolation: class MyClass<T> { func genericName() -> String { return “\(T.self)” } } You can try it in a playground and it works as expected: var someClass = MyClass<String>() someClass.genericName() // Returns “Swift.String”
You can use model’s _meta attribute to get field object and from field you can get relationship and much more e.g. consider a employee table which has a foreign key to a department table In [1]: from django.db import models In [2]: model = models.get_model(‘timeapp’, ‘Employee’) In [3]: dep_field = model._meta.get_field_by_name(‘department’) In [4]: dep_field[0].target_field Out[4]: … Read more
The stack frame tells us what code object we’re in. If we can find a function object that refers to that code object in its __code__ attribute, we have found the function. Fortunately, we can ask the garbage collector which objects hold a reference to our code object, and sift through those, rather than having … Read more
Extract the attributes in to an array, assign them to a constant, then splat them in to attr_accessor. class SubClass < MyBaseClass ATTRS = [:id, :title, :body] attr_accessor(*ATTRS) end Now you can access them via the constant: puts SubClass.ATTRS #=> [:id, :title, :body]