@@ -518,53 +518,56 @@ desired effect in a number of ways.
518
518
519
519
1) By returning a tuple of the results::
520
520
521
- def func2 (a, b):
522
- a = 'new-value' # a and b are local names
523
- b = b + 1 # assigned to new objects
524
- return a, b # return new values
525
-
526
- x, y = 'old-value', 99
527
- x, y = func2 (x, y)
528
- print(x, y) # output: new-value 100
521
+ >>> def func1 (a, b):
522
+ ... a = 'new-value' # a and b are local names
523
+ ... b = b + 1 # assigned to new objects
524
+ ... return a, b # return new values
525
+ ...
526
+ >>> x, y = 'old-value', 99
527
+ >>> func1 (x, y)
528
+ (' new-value', 100)
529
529
530
530
This is almost always the clearest solution.
531
531
532
532
2) By using global variables. This isn't thread-safe, and is not recommended.
533
533
534
534
3) By passing a mutable (changeable in-place) object::
535
535
536
- def func1(a):
537
- a[0] = 'new-value' # 'a' references a mutable list
538
- a[1] = a[1] + 1 # changes a shared object
539
-
540
- args = ['old-value', 99]
541
- func1(args)
542
- print(args[0], args[1]) # output: new-value 100
536
+ >>> def func2(a):
537
+ ... a[0] = 'new-value' # 'a' references a mutable list
538
+ ... a[1] = a[1] + 1 # changes a shared object
539
+ ...
540
+ >>> args = ['old-value', 99]
541
+ >>> func2(args)
542
+ >>> args
543
+ ['new-value', 100]
543
544
544
545
4) By passing in a dictionary that gets mutated::
545
546
546
- def func3(args):
547
- args['a'] = 'new-value' # args is a mutable dictionary
548
- args['b'] = args['b'] + 1 # change it in-place
549
-
550
- args = {'a': 'old-value', 'b': 99}
551
- func3(args)
552
- print(args['a'], args['b'])
547
+ >>> def func3(args):
548
+ ... args['a'] = 'new-value' # args is a mutable dictionary
549
+ ... args['b'] = args['b'] + 1 # change it in-place
550
+ ...
551
+ >>> args = {'a': 'old-value', 'b': 99}
552
+ >>> func3(args)
553
+ >>> args
554
+ {'a': 'new-value', 'b': 100}
553
555
554
556
5) Or bundle up values in a class instance::
555
557
556
- class callByRef:
557
- def __init__(self, /, **args):
558
- for key, value in args.items():
559
- setattr(self, key, value)
560
-
561
- def func4(args):
562
- args.a = 'new-value' # args is a mutable callByRef
563
- args.b = args.b + 1 # change object in-place
564
-
565
- args = callByRef(a='old-value', b=99)
566
- func4(args)
567
- print(args.a, args.b)
558
+ >>> class Namespace:
559
+ ... def __init__(self, /, **args):
560
+ ... for key, value in args.items():
561
+ ... setattr(self, key, value)
562
+ ...
563
+ >>> def func4(args):
564
+ ... args.a = 'new-value' # args is a mutable Namespace
565
+ ... args.b = args.b + 1 # change object in-place
566
+ ...
567
+ >>> args = Namespace(a='old-value', b=99)
568
+ >>> func4(args)
569
+ >>> vars(args)
570
+ {'a': 'new-value', 'b': 100}
568
571
569
572
570
573
There's almost never a good reason to get this complicated.
0 commit comments