Get value from string representing local variable
You can use eval
.
variable = 22
eval("variable")
# => 22
However eval
can be nasty. If you dont mind declaring an instance variable, you can do something like this too:@variable = 22
str = "variable"
instance_variable_get("@#{str}")
# => 22
Access a methods local variable value using a string containing the variable name in .Net
Local variables aren't representing in reflection. You can see globals because they're members of a type. Locals, however, are just slots on the current stack, and that stack isn't exposed to the reflection APIs.
The only place that the call stack is exposed programmatically is in the stack trace in an exception. You could throw an exception deliberately, catch it, and pick through the stack trace. But it would be a bad, bad, idea, and extremely slow.
Get property from local variable by string
In general, you can't get values of local variables at runtime (see this question for reference), but based on my own answer from another question, you can use method GetPropertyValue
to workaround this problem creating a local object with desired properties:
public void SomeMethod()
{
var container = new
{
user = userWS.GetUsers(),
documents = documentWS.GetDocuments()
}
// returns: "user.username.value"
string usernameProperty = GetMapperValueById ( "username" );
var value = GetPropertyValue(container, usernameProperty);
}
static object GetPropertyValue(object obj, string propertyPath)
{
System.Reflection.PropertyInfo result = null;
string[] pathSteps = propertyPath.Split('.');
object currentObj = obj;
for (int i = 0; i < pathSteps.Length; ++i)
{
Type currentType = currentObj.GetType();
string currentPathStep = pathSteps[i];
var currentPathStepMatches = Regex.Match(currentPathStep, @"(\w+)(?:\[(\d+)\])?");
result = currentType.GetProperty(currentPathStepMatches.Groups[1].Value);
if (result.PropertyType.IsArray)
{
int index = int.Parse(currentPathStepMatches.Groups[2].Value);
currentObj = (result.GetValue(currentObj) as Array).GetValue(index);
}
else
{
currentObj = result.GetValue(currentObj);
}
}
return currentObj;
}
Access variable value using string representing variable's name in C++
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
how get values from object to local variable c#
You should cast the object to the class
it originally is (what class is the object
returned by GetBookingFromAPI()
) before you could access its field/property/method
. Example:
public MyClass { // suppose this is the original class of the object returned by GetBookingFromAPI
public int booking_id;
}
APIKarho objapi = new APIKarho();
object obje = objapi.GetBookingFromAPI();
string ss = ((MyClass)obje).booking_id; //note the casting to MyClass here
Getting the name of a variable as a string
TL;DR
Use the Wrapper
helper from python-varname
:
from varname.helpers import Wrapper
foo = Wrapper(dict())
# foo.name == 'foo'
# foo.value == {}
foo.value['bar'] = 2
For list comprehension part, you can do:n_jobs = Wrapper(<original_value>)
users = Wrapper(<original_value>)
queues = Wrapper(<original_value>)
priorities = Wrapper(<original_value>)
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [d.name for d in list_of_dicts]
# ['n_jobs', 'users', 'queues', 'priorities']
# REMEMBER that you have to access the <original_value> by d.value
I am the author of the python-varname
package. Please let me know if you have any questions or you can submit issues on Github.The long answer
Is it even possible?
Yes and No.We are retrieving the variable names at runtime, so we need a function to be called to enable us to access the previous frames to retrieve the variable names. That's why we need a Wrapper
there. In that function, at runtime, we are parsing the source code/AST nodes in the previous frames to get the exact variable name.
However, the source code/AST nodes in the previous frames are not always available, or they could be modified by other environments (e.g: pytest
's assert
statement). One simple example is that the codes run via exec()
. Even though we are still able to retrieve some information from the bytecode, it needs too much effort and it is also error-prone.
How to do it?
First of all, we need to identify which frame the variable is given. It's not always simply the direct previous frame. For example, we may have another wrapper for the function:from varname import varname
def func():
return varname()
def wrapped():
return func()
x = wrapped()
In the above example, we have to skip the frame inside wrapped
to get to the right frame x = wrapped()
so that we are able to locate x
. The arguments frame
and ignore
of varname
allow us to skip some of these intermediate frames. See more details in the README file and the API docs of the package.Then we need to parse the AST node to locate where the variable is assigned value (function call) to. It's not always just a simple assignment. Sometimes there could be complex AST nodes, for example, x = [wrapped()]
. We need to identify the correct assignment by traversing the AST tree.
How reliable is it?
Once we identify the assignment node, it is reliable.varname
is all depending on executing
package to look for the node. The node executing detects is ensured to be the correct one (see also this).
It partially works with environments where other AST magics apply, including pytest, ipython, macropy, birdseye, reticulate with R, etc. Neither executing nor varname is 100% working with those environments.
Do we need a package to do it?
Well, yes and no, again.If your scenario is simple, the code provided by @juan Isaza or @scohe001 probably is enough for you to work with the case where a variable is defined at the direct previous frame and the AST node is a simple assignment. You just need to go one frame back and retrieve the information there.
However, if the scenario becomes complicated, or we need to adopt different application scenarios, you probably need a package like python-varname
, to handle them. These scenarios may include to:
- present more friendly messages when the source code is not available or AST nodes are not accessible
- skip intermediate frames (allows the function to be wrapped or called in other intermediate frames)
- automatically ignores calls from built-in functions or libraries. For example:
x = str(func())
- retrieve multiple variable names on the left-hand side of the assignment
- etc.
f-string
?Like the answer provided by @Aivar Paalberg. It's definitely fast and reliable. However, it's not at runtime, meaning that you have to know it's foo
before you print the name out. But with varname
, you don't have to know that variable is coming:
from varname import varname
def func():
return varname()
# In external uses
x = func() # 'x'
y = func() # 'y'
Finally
python-varname
is not only able to detect the variable name from an assignment, but also:- Retrieve variable names directly, using
nameof
- Detect next immediate attribute name, using
will
- Fetch argument names/sources passed to a function using
argname
However, the final word I want to say is that, try to avoid using it whenever you can.
Because you can't make sure that the client code will run in an environment where the source node is available or AST node is accessible. And of course, it costs resources to parse the source code, identify the environment, retrieve the AST nodes and evaluate them when needed.
In Python, how do I get a variable via a string representation of the name of the variable?
If hasattr(self,s)
, is sufficient to your needs, then you want getattr()
:
if hasattr(self, s):
print getattr(self, s)
In fact, you may be able to skip the hasattr
altogether, depending upon your precise requirement. getattr()
takes a default value to return if the attribute is missing:print gettattr(self, s, 'No such attribute: '+s)
If you want to find variables outside of the current object (say, in local scope or global scope, or in another object), try one of these:locals()[s]
globals()[s]
getattr(other_object, s)
Note: using locals()
, globals()
, and to a lesser extent, hasattr(self,s)
, outside of a few limited cases, is a code smell. It almost very likely means that your design is flawed.
Related Topics
How to Remove Ruby on Rails 4 Beta
Thor Executable - Ignore Task Name
Timeout When Installing Ruby Gems
Many to Many Table with an Extra Column in Rails
Rvm Finding System Gems' Executables
Rails Asset Pipeline and Digest Values
What Is Returned in Ruby If The Last Statement Evaluated Is an If Statement
Can't Get Paypal Encrypted Website Payments to Work in Rails
Get All Products of Category and Child Categories (Rails, Awesome_Nested_Set)
Ruby-Open3.Popen3/How to Print The Output
Require Tree in Asset Pipeline
How to Open File in Default Application. Ruby
Regex That Matches Valid Ruby Local Variable Names
Devise with Ruby on Rails - Force User to Change Password on First Login