0

There is a legacy code that I am looking into, there are many variables being used while importing excel sheet. Now I want to apply strip function to the variables if they are of type str and then could normally access them via their name.

I tried,like this

lvars = locals()
for k, v in lvars.items():
        if(isinstance(lvars[k], str)):
            lvars[k] = v.strip()

As far as I could research there is no way to update local variables in python by calling locals or any other means.

Is there a way to do so? I know I can use a dictionary to store the local vars and later access them via it but that would require a lot of update in the code too since I would like to access vars directly via their name.

  • @kaya3. I don't understand the relation between your link and the question of OP? – Corralien Mar 25 '22 at 07:34
  • "As far as I could research there is no way to update local variables in python by calling locals or any other means." yes. CPython does not expose any way to dynamically modify local namespaces, since they are optimized and are not merely `dict` objects like global namespaces. Generally, there is no good reason to. What you are trying to do just sounds like building a house of cards – juanpa.arrivillaga Mar 25 '22 at 07:37
  • "Variable variables" means accessing variables other than by a static name. In this case OP wants to loop over each local variable and reassign the string-valued ones, which would require accessing and changing variables without referring to each one by its static name. That is not possible for local variables, as explained in the linked Q&A, you must use your own data structure such as a dictionary for the purpose. – kaya3 Mar 25 '22 at 07:38
  • 2
    To be honest this is really an [XY problem](https://xyproblem.info); the strings are coming from a spreadsheet so they should be stripped once, together, when they are read from the spreadsheet, before individual strings are assigned to any local variables. – kaya3 Mar 25 '22 at 07:43

0 Answers0