Python Forum
Results name is a variable itself
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Results name is a variable itself
#1
Hi
I do not remember how to proceed for the following assignment without using (hugly) local, global, and so on; the name if the function is itself a variable (it looks like the following snippet)
Thanks for refreshing my memory
Paul

NamesList = ['name1', 'name2', 'name3']
NamesList[0] = myfunction()
Reply
#2
What exactly do you want to do? There is no problem in what you are showing us.
def myfunction():
    return "name4"

NamesList = ['name1', 'name2', 'name3']
NamesList[0] = myfunction()
print(NamesList)
Output:
['name4', 'name2', 'name3']
If on the other hand you want the list to contain a function, you have to omit the parentheses when assigning the value. Then, when using the value you have to supply the parentheses.
NamesList[0] = myfunction
print(NamesList[0]())
Output:
name4
Reply
#3
I do not understand what you are trying to do. Do you want to make a variable named "name1" that references a function? If so, why? What's wrong with the name "myfunction"? If you want the function to be called "name1" why didn't you name it that in the first place? Dynamically creating variables in Python is possible, but discouraged. The purpose of a variable is to have a convenient name for referencing something. A name the program knows. Dynamically creating variables kind of defeats the whole purpose of variables.

It can be useful to have a dictionary of functions. There are a lot of my first calculator programs that do this:
import operator

operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv
}

while True:
    eq = input("Enter equation: ").split()
    if len(eq) != 3:
        break
    a, op, b = eq
    print(a, op, b, '=', operators[op](float(a), float(b)))
Here I effectively give operator.add the name "+", but I did not create a "+" variable (it is impossible).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,245 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  How to append one function1 results to function2 results SriRajesh 5 3,179 Jan-02-2020, 12:11 PM
Last Post: Killertjuh

Forum Jump:

User Panel Messages

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