开发者

Can I add a second name to a variable

开发者 https://www.devze.com 2023-04-13 08:51 出处:网络
I need to convince myself that this is a bad idea.I want to assign a second name to the same variable, whose contents may change.

I need to convince myself that this is a bad idea. I want to assign a second name to the same variable, whose contents may change.

A='Bob'
B=A #wrong function, I want to figure out something that works here.
A='Alice'
print A
print B

I want both A and B to print 'Alice' but instead B prints 'Bob' 开发者_如何学Goand A prints 'Alice'.

Why do I want to do this? In my code I am using one name for a bit of data, that makes sense for processing, but a different name makes sense for user input. argparse seems to want to assign a variable name based on the command line option. So I want to use one name when the data is entered, but another name when it is processed. I would prefer to avoid copying one to the other, but that is my fallback position.


Python strings are immutable:

In Python the string object is immutable - each time a string is assigned to a variable a new object is created in memory to represent the new value.

Wikipedia doc on immutability and specific Python example.

One simple way to get the behavior you want is to wrap a string in a class thusly:

class MyClass:
    SomeStr = "Any Val"

A = MyClass
A.SomeStr = "Bob"
B=A
B.SomeStr = "Alice"

print(A.SomeStr)
print(B.SomeStr)

Output:

>>> 
Alice
Alice

So now your B=A assignment creates a "shallow" copy... The two variables, A & B point to the same object.


If you really want to be convinced that it's a bad idea, maybe for your argparse example you'd want to rename the variable being used to be differently from the option name. Use the dest option of argparse.add_argument

Only one of the examples from the doc:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')


I'd argue that the processing part should be a separate module from the input part, so neither should have any reason to know about the other. Input the data and store it in an appropriate place, and pass it to the processing part as a parameter using whatever name you want.


You can only do this for values which Python consider variables to names of references to, e.g. lists, dictionaries, and so on.

A=["Bob"]
B=A
A[0] = "Alice"
print A, B

will print "Alice" twice.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号