Can I define a function which, when called, inserts new locals into the caller’s scope? I have a feeling that passing the caller’s locals() into the function might work, but is there a way to do what I want without having to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By Python’s rules, you cannot alter your caller’s
locals; in the current implementations, if you try (e.g. with the black magic Anurag suggests) you will not get an exception (though I’d like to add that error check to some future version), but it will be essentially inoperative if your caller is a function (not if your caller is module top-level code) — the caller’s actual local variables won’t in fact be affected. This holds whether the caller’slocalsare explicitly passed in, or fetched through black magic: they still need to be treated as a read-only dict if your code is to have any sanity.Rather, you could have the caller pass in an explicit, real, normal dict (which could be initialized from
locals()if you want), and all alterations your code does in that dict will still be there for the caller’s use — just not as “new barenames” in the caller’s local scope of course, but the functionality is the same whether the caller needs to usex['foo']orx.fooor (as you’d prefer) just barenamefoo.BTW, to use attribute-access syntax rather than dict indexing syntax, you can do:
This also covers, with a tiny variation, the case in which
thefunwants to work with dict indexing syntax (say its body isb['foo'] = 23instead ofb.foo = 23): in that case, the caller just needs to usethefun(vars(b))instead of the plainthefun(b), but it can keep working with theb.fooaccess syntax afterwards.