Can this be easily done in Python?
Matt Wheeler
m at funkyhat.org
Wed Sep 28 08:26:28 EDT 2016
On Tue, 27 Sep 2016 at 20:58 TUA <kai.peters at gmail.com> wrote:
> Is the following possible in Python?
>
> Given how the line below works
>
> TransactionTerms = 'TransactionTerms'
>
>
> have something like
>
> TransactionTerms = <some Python code here>
>
> that sets the variable TransactionTerms to its own name as string
> representation without having to specify it explicitly as in the line
> above....
>
(forgot to send to list, sorry)
```
def name(name):
globals()[name] = name
name('hi')
print(hi)
```
Or alternatively
```
import inspect
def assign():
return inspect.stack()[1].code_context[0].split('=')[0].strip()
thing = assign()
print(thing)
```
But why?
Both of these are pretty dodgy abuses of Python (I can't decide which
is worse, anyone?), and I've only tested them on 3.5. I present them
here purely because I was interested in working them out, and absolve
myself of any responsibility should anyone find them in use in
production code! :P (don't do that!)
More information about the Python-list
mailing list