Python Forum
How to assign a module to a variable even if it's not defined?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to assign a module to a variable even if it's not defined?
#6
(Aug-12-2020, 03:16 PM)mandaxyz Wrote: The terms say that I come back if I find the solution. I use 'exec' to create a variable from string.
Yes,but a better way could be to use a data structure like dictionary.
What's really happens when do exec("abc=123") or just abc = 123,is that Python map this to a internal global dictionary.
>>> exec("abc = 123")
>>> globals()['abc']
123
>>> type(globals())
<class 'dict'>
So the way to make this more clear is to use real visible dictionary.
>>> d = dict(abc=123, foo=456)
>>> d
{'abc': 123, 'foo': 456}
>>> d['abc']
123

# Then also get method like get
>>> d.get('abc', 'Not in record')
123
>>> d.get('abcd', 'Not in record')
'Not in record'
>>> d.get('foo', 'Not in record')
456
mandaxyz Wrote:Bye, I will make effort next time, I will try to be perfect
To be perfect is a goal we all will fail at Wink
I think just a little expatiation of the goal of doing this was the point here.
Reply


Messages In This Thread
RE: How to assign a module to a variable even if it's not defined? - by snippsat - Aug-12-2020, 10:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 3 291 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 594 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,319 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  [variable] is not defined error arises despite variable being defined TheTypicalDoge 4 2,139 Apr-05-2022, 04:55 AM
Last Post: deanhystad
  Error when refering to class defined in 'main' in an imported module HeRo 2 2,412 Apr-13-2021, 07:22 PM
Last Post: HeRo
  When I print a key from dict it prints it but when I try to assign it to a variable I stefanvelikov 3 2,370 Nov-27-2020, 01:29 PM
Last Post: stefanvelikov
  Function will not return variable that I think is defined Oldman45 6 3,532 Aug-18-2020, 08:50 PM
Last Post: deanhystad
  Variable not defined Heyjoe 4 2,570 Jul-10-2020, 11:27 PM
Last Post: Heyjoe
  python library not defined in user defined function johnEmScott 2 3,877 May-30-2020, 04:14 AM
Last Post: DT2000
  Error: variable can not be defined julio2000 2 3,207 Feb-09-2020, 08:51 PM
Last Post: julio2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020