Let's assume we have an exposed function (Level 0). We call this function with various parameter. Internally this function calls a second function (Level 1) but does not use any of the given parameters other than calling a third function (Level 2) with them as arguments. It might do some other stuff however.
My Question is. How can we pass down the arguments without creating too much noise in the middle layer function (Level 1)? I list some possible ways beneath. Be warned however that some of them are rather ugly and only there for completeness reasons. I'm looking for some established guideline rather than individual personal opinion on the topic
# Transport all of them individually down the road.
# This is the most obvious way. However the amount of parameter increases the
# noise in A_1 since they are only passed along
def A_0(msg, term_print):
A_1(msg, term_print)
def A_1(msg, term_print):
A_2(msg, term_print)
def A_2(msg, term_print):
print(msg, end=term_print)
# Create parameter object (in this case dict) and pass it down.
# Reduces the amount of parameters. However when only reading the source of B1
# it is impossible to determine what par is
def B_0(msg, term_print):
B_1({'msg': msg, 'end': term_print})
def B_1(par):
B_2(par)
def B_2(par):
print(par['msg'], end=par['end'])
# Use global variables. We all know the pitfalls of global variables. However
# in python there are at least limited to their module
def C_0(msg, term_print):
global MSG, TERM_PRINT
MSG = msg
TERM_PRINT = term_print
C_1()
def C_1():
C_2()
def C_2():
print(MSG, end=TERM_PRINT)
# Use the fact that python creates function objects. We can now append those
# objects. This makes some more 'localised' variables than shown before. However
# this also makes the code harder to maintain. When we change D_2 we have to alter
# D_0 as well even though it never directly calls it
def D_0(msg, term_print):
D_2.msg = msg
D_2.term_print = term_print
D_1()
def D_1():
D_2()
def D_2():
print(D_2.msg, end=D_2.term_print)
# Create a class with the functions E_1, E_2 to enclose the variables.
class E(dict):
def E_1(self):
self.E_2()
def E_2(self):
print(self['msg'], end=self['end'])
def E_0(msg, term_print):
E([('msg', msg), ('end', term_print)]).E_1()
# Create a nested scope. This make it very hard to read the function. Furthermore
# F_1 cannot be called directly from outside (without abusing the construct)
def F_0(msg, term_print):
def F_1():
F_2()
def F_2():
print(msg, end=term_print)
F_1()
A_0('What', ' ')
B_0('is', ' ')
C_0('the', ' ')
D_0('best', ' ')
E_0('way', '')
F_0('?', '\n')
It's hard to give a complete answer without knowing the full specifics of why there are so many parameters and so many levels of functions. But in general, passing too many parameters is considered a code smell.
Generally, if a group of functions all make use of the same parameters, it means they are closely related in some way, and may benefit from encapsulating the parameters within a Class, so that all the associated methods can share that data.
TooManyParameters is often a CodeSmell. If you have to pass that much
data together, it could indicate the data is related in some way and
wants to be encapsulated in its own class. Passing in a single
data structure that belongs apart doesn't solve the problem. Rather,
the idea is that things that belong together, keep together; things
that belong apart, keep apart; per the OneResponsibilityRule.
Indeed, you may find that entire functions are completely unnecessary if all they are doing is passing data along to some other function.
class A():
def __init__(self, msg, term_print)
self.msg = msg
self.term_print = term_print
def a_0(self):
return self.a_1()
def a_1(self):
return self.a_2()
def a_2(self):
print(msg, self.term_print)
Depending on the meaning of your sets of parameters and of your function A0, using the *args notation may also be an option:
def A0(*args):
A1(*args)
This allows any number of arguments to be passed to A0 and will pass them on to A1 unchanged. If the semantics of A0 is just that, then the * notation expresses the intention best. However, if you are going to pass on the arguments in a different order or do anything else with them besides just passing them on as an opaque sequence, this notation is not a good fit.
The book "Code Complete 2" by Steve McConnell suggests to use globals, their words are:
Reasons to Use Global Data
Eliminating tramp data
Sometimes you pass data to a routine or class
merely so that it can be passed to another routine or class. For
example, you might have an error-processing object that's used in each
routine. When the routine in the middle of the call chain doesn't use
the object, the object is called "tramp data". Use of global variables can eliminate tramp data.
Use Global Data Only as a Last Resort
Before you resort to using global data
consider a few alternatives:
Begin by making each variable local and make variables global only as you need to
Make all variables local to individual routines initially. If you find
they're needed elsewhere, make them private or protected class
variables before you go so far as to make them global. If you finally
find that you have to make them global, do it, but only when you're
sure you have to. If you start by making a variable global, you'll
never make it local, whereas if you start by making it local, you
might never need it to make it global.
Distinguish between global and class variables
Some variables are truly global in that they are accessed throughout
the whole program. Others are really class variables, used heavily
only within a certain set of routines. It's OK to access a class
variable any way you want to within the set of routines that use it
heavily. If routines outside the class need to use it, provide the
variable's value by means of an access routine. Don't access class
values direcly - as if they were global variables - even if your
programming language allows you to. This advice is tantamount to
saying "Modularize! Modularize! Modularize"
Use access routines
Creating access routines is the workhorse approach to getting around
problems with global data...
Link:
https://books.google.com/books/about/Code_Complete.html?hl=nl&id=LpVCAwAAQBAJ
Related
I am making a program to do some calculations for my Microeconomics class. Since there are some ways of working depending on the problem I am given, I have created a class. The class parses an Utility function and a 'mode' from the command line and calls a function or another depending on the mode.
Since every function uses the same variables I initiate them in __init__():
self.x = x = Symbol('x') # Variables are initiated
self.y = y = Symbol('y')
self.Px, self.Py, self.m = Px, Py, m = Symbol('Px'), Symbol('Py'), Symbol('m')
I need a local definition to successfully process the function. Once the function is initiated through sympify() I save it as an instance variable:
self.function = sympify(args.U)
Now I need to pass the variables x,yPx,Py,m to the different functions. This is where I have the problem. As I want a local definition I could simply x=self.x with all the variables. I would need to repeat this in every piece of code which isn't really sustainable. Another option is to pass all the variables as arguments.
But since I'm using a dictionary to choose which function to call depending on the mode this would mean I have to pass the same arguments for every function, whether I use them or not.
So I have decided to create a dictionary such as:
variables = { #A dictionary of variables is initiated
'x':self.x,
'y':self.y,
'Px':self.Px,
'Py':self.Py,
'm':self.m
}
This dictionary is initiated after I declare the variables as sympy Symbols. What I would like is to pass this dictionary in an unpacked form to every function. This way i would only need **kwargs as an argument and I could use the variables I want.
What I want is something like this:
a = 3
arggs = {'a' = a}
def f(**kwargs):return a+1
f(**args)
This returns 4. However when I pass my dictionary as an argument I get a non-defined 'x' or 'y' variables error. It can't be an scope issue because all the variables have been initiated for all the instance.
Here is my code calling the function:
self.approaches[self.identification][0](**self.variables)
def default(self, **kwargs):
solutions = dict()
self.MRS = S(self.function.diff(x) / self.function.diff(y)) # This line provokes the exception
What's my error?
PS: Some information may be unclear. English is not my main language. Apologies in advance.
Unfortunately, Python doesn't quite work like that. When you use **kwargs, the only variable this assigns is the variable kwargs, which is a dictionary of the keyword arguments. In general, there's no easy way to inject names into a function's local namespace, because of the way locals namespaces work. There are ways to do it, but they are fairly hacky.
The easiest way to make the variables available without having to define them each time is to define them at the module level. Generally speaking, this is somewhat bad practice (it really does belong on the class), but since SymPy Symbols are immutable and defined entirely by their name (and assumptions if you set any), it's just fine to set
Px, Py, m = symbols("Px Py m")
at the module level (i.e., above your class definition), because even if some other function defines its own Symbol("Px"), SymPy will consider it equal to the Px you defined from before.
In general, you can play somewhat fast and loose with immutable objects in this way (and all SymPy objects are immutable) because it doesn't really matter if an immutable object gets replaced with a second, equal object. It would matter, if, say, you had a list (a mutable container) because it would make a big difference if it were defined on the module level vs. the class level vs. the instance level.
Let's say I have a code like this:
def read_from_file(filename):
list = []
for i in filename:
value = i[0]
list.append(value)
return list
def other_function(other_filename):
"""
That's where my question comes in. How can I get the list
from the other function if I do not know the value "filename" will get?
I would like to use the "list" in this function
"""
read_from_file("apples.txt")
other_function("pears.txt")
I'm aware that this code might not work or might not be perfect. But the only thing I need is the answer to my question in the code.
You have two general options. You can make your list a global variable that all functions can access (usually this is not the right way), or you can pass it to other_function (the right way). So
def other_function(other_filename, anylist):
pass # your code here
somelist = read_from_file("apples.txt")
other_function("pears.txt.", somelist)
You need to "catch" the value return from the first function, and then pass that to the second function.
file_name = read_from_file('apples.txt')
other_function(file_name)
You need to store the returned value in a variable before you can pass it onto another function.
a = read_from_file("apples.txt")
There are at least three reasonable ways to achieve this and two which a beginner will probably never need:
Store the returned value of read_from_file and give it as a parameter to other_function (so adjust the signature to other_function(other_filename, whatever_list))
Make whatever_list a global variable.
Use an object and store whatever_list as a property of that object
(Use nested functions)
(Search for the value via garbage collector gc ;-)
)
Nested functions
def foo():
bla = "OK..."
def bar():
print(bla)
bar()
foo()
Global variables
What are the rules for local and global variables in Python? (official docs)
Global and Local Variables
Very short example
Misc
You should not use list as a variable name as you're overriding a built-in function.
You should use a descriptive name for your variables. What is the content of the list?
Using global variables can sometimes be avoided in a good way by creating objects. While I'm not always a fan of OOP, it sometimes is just what you need. Just have a look of one of the plenty tutorials (e.g. here), get familiar with it, figure out if it fits for your task. (And don't use it all the time just because you can. Python is not Java.)
Can you please help me guys. I believe I've got pretty easy questions but don't want to stuff up with my assignment. I'm going to have Class in my module, this class will have few functions.
I just want to be sure it works alright and this is a not ugly code practice.
I.e. my first function test_info accepts one parameter test_code and returns something and the second function check_class accepts two parameter, one of them is called test_code as well
Can I use same argument name: test_code? Is it normal code practice?
def test_info (self, test_code):
my_test_code = test_code
#here we'll be using my_test_code to get info from txt file and return other info
def check_class (self, test_code, other_arg):
my_test_code = test_code
#here some code goes
Also is it fine to use my_test_code in both functions to get argument value or is it better to use different ones like my_test_code_g etc.
Many thanks
Yes you may.
The two variables test_code are defined only in the scope of their respective functions and therefore will not interfere with one another since the other functions lie outside their scope.
Same goes for my_test_code
Read online about variable scopes. Here is a good start
There is no technical reason to resolve this one way or another. But if the variables don't serve exactly the same purpose in both functions, it's confusing for a human reader if they have the same name.
Say I had a function in Python:
def createCube(no_of_cubes):
This function creates cubes and the number of cubes it creates is set by the parameter: no_of_cubes
If i then wanted to create another function:
def moveCubes():
and I wanted the parameter no_of_cubes to be used in this function, and for the parameter to use the same integer that has been inputted for the first function. How would I do so? Or is it not possible?
A parameter is merely an argument to a function, much like you'd have in a maths function, e.g. f(x) = 2*x. Also like in maths, you can define infinite questions with the same arguments, e.g. g(x) = x^2.
The name of the parameter doesn't change anything, it's just how your function is gonna call that value. You could call it whatever you wanted, e.g. f(potato) = 2 * potato. However, there are a few broad naming conventions—in maths, you'd give preference to a lowercase roman letter for a real variable, for example. In programming, like you did, you want to give names that make sense—if it refers to the number of cubes, calling it no_of_cubes makes it easier to read your program than calling it oquhiaisnca, so kudos on that.
I'm not sure how that bit fits into your program. A few of the other answers suggested ways to do it. If it's just two loose functions (not part of a class), you can define a variable outside the functions to do what you want, like this:
1: n = 4 # number of cubes, bad variable name
2: def createCube(no_of_cubes):
3: # things
4: def moveCubes(no_of_cubes):
5: # different things
6: createCube(n)
7: moveCubes(n)
What happens here is that line 6 calls the function createCube and gives it n (which is 4) as a parameter. Then line 7 calls moveCubes giving it the same n as a parameter.
This is a very basic question, so I'm assuming you're new to programming. It might help a lot if you take some python tutorial. I recommend Codecademy, but there are several others you can choose from. Good luck!
It is possible. But that two definitions get that parameter as their own one. I mean that parameter works only the definition scope. It may not be harmful for another same name parameter on different definitions.
If you cannot, probably you shouldn't do it.
If they're two separate functions (not nested or so), they should not share parameters.
If they do have connection in some way, a better way is to define a class:
class Cube:
def __init__(self, no_of_cubes):
self.no_of_cubes = no_of_cubes
def create_cube(self):
# use self.no_of_cubes
pass
def move_cubes(self):
# use self.no_of_cubes
pass
c = Cube(no_of_cubes)
c.create_cube()
c.move_cubes
Unless you know what you're doing, don't define global variable.
You can load the function moveCubes() inside createCube(). For example:
def createCube(no_of_cubes):
# Do stuff
moveCubes(no_of_cubes)
def moveCubes(no_of_cubes):
# Do more stuff
Or you could define no_of_cubes out of the functions so it is accessible to all.
no_of_cubes = 5
def createCube():
global no_of_cubes
# Do stuff
def moveCubes():
global no_of_cubes
# Do stuff
I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the behaviour or the program I find that I end up requiring this user-defined parameter in a method in a.py that is not directly called by main.py, but is instead called by another method in a.py:
main.py:
import a
p = some_command_line_argument_value
a.meth1(p)
a.py:
meth1(p):
# some code
res = meth2(p)
# some more code w/ res
meth2(p):
# do something with p
This excessive parameter passing seems wasteful and wrong, but has hard as I try I cannot think of a design pattern that solves this problem. While I had some formal CS education (minor in CS during my B.Sc.), I've only really come to appreciate good coding practices since I started using python. Please help me become a better programmer!
Create objects of types relevant to your program, and store the command line options relevant to each in them. Example:
import WidgetFrobnosticator
f = WidgetFrobnosticator()
f.allow_oncave_widgets = option_allow_concave_widgets
f.respect_weasel_pins = option_respect_weasel_pins
# Now the methods of WidgetFrobnosticator have access to your command-line parameters,
# in a way that's not dependent on the input format.
import PlatypusFactory
p = PlatypusFactory()
p.allow_parthenogenesis = option_allow_parthenogenesis
p.max_population = option_max_population
# The platypus factory knows about its own options, but not those of the WidgetFrobnosticator
# or vice versa. This makes each class easier to read and implement.
Maybe you should organize your code more into classes and objects? As I was writing this, Jimmy showed a class-instance based answer, so here is a pure class-based answer. This would be most useful if you only ever wanted a single behavior; if there is any chance at all you might want different defaults some of the time, you should use ordinary object-oriented programming in Python, i.e. pass around class instances with the property p set in the instance, not the class.
class Aclass(object):
p = None
#classmethod
def init_p(cls, value):
p = value
#classmethod
def meth1(cls):
# some code
res = cls.meth2()
# some more code w/ res
#classmethod
def meth2(cls):
# do something with p
pass
from a import Aclass as ac
ac.init_p(some_command_line_argument_value)
ac.meth1()
ac.meth2()
If "a" is a real object and not just a set of independent helper methods, you can create an "p" member variable in "a" and set it when you instantiate an "a" object. Then your main class will not need to pass "p" into meth1 and meth2 once "a" has been instantiated.
[Caution: my answer isn't specific to python.]
I remember that Code Complete called this kind of parameter a "tramp parameter". Googling for "tramp parameter" doesn't return many results, however.
Some alternatives to tramp parameters might include:
Put the data in a global variable
Put the data in a static variable of a class (similar to global data)
Put the data in an instance variable of a class
Pseudo-global variable: hidden behind a singleton, or some dependency injection mechanism
Personally, I don't mind a tramp parameter as long as there's no more than one; i.e. your example is OK for me, but I wouldn't like ...
import a
p1 = some_command_line_argument_value
p2 = another_command_line_argument_value
p3 = a_further_command_line_argument_value
a.meth1(p1, p2, p3)
... instead I'd prefer ...
import a
p = several_command_line_argument_values
a.meth1(p)
... because if meth2 decides that it wants more data than before, I'd prefer if it could extract this extra data from the original parameter which it's already being passed, so that I don't need to edit meth1.
With objects, parameter lists should normally be very small, since most appropriate information is a property of the object itself. The standard way to handle this is to configure the object properties and then call the appropriate methods of that object. In this case set p as an attribute of a. Your meth2 should also complain if p is not set.
Your example is reminiscent of the code smell Message Chains. You may find the corresponding refactoring, Hide Delegate, informative.