[Tutor] using a variable inside function, provided the variable is assigned a value after the function definition

Alan Gauld alan.gauld at yahoo.co.uk
Sun Sep 19 04:06:16 EDT 2021


On 19/09/2021 08:11, Manprit Singh wrote:

> def sumofnumber(x):
>     return x+b
> 
> b = 3
> a = 4
> ans = sumofnumber(a)
> print(ans)   gives the answer = 7 which is the sum of 4 & 3 .

> A variable which is assigned a value below or after  the function
> definition , can be used inside that function definition or not ? is it a
> good practise ?

As you've already seen Python doesn't care, so technically it works.

But it is very bad practice to rely on global variables inside a function.

If the function has to add two numbers then two numbers should
be passed in and a result returned. That way the function is
reusable in contexts that do not have a variable called b
(or use b for some other purpose)

In addition the use of an external variable makes the function
much more difficult to maintain since the reader has to scan
the external code to find out what and where b is. Additionally,
if other functions change b as well it becomes very difficult
to know or predict the program behaviour, especially in concurrency
scenarios.

About the only scenario where it is a reasonable thing to do is
if b is actually a constant (in which case style says it should
be B not b) and therefore never changed.  Otherwise always pass
in the data your functions need.

The other related scenario is inside a class where the methods
all access the shared attributes. But that is an order of
magnitude less troublesome since it is the object that gets
reused not the methods, and the attributes are encapsulated
with the methods for maintenance. That leaves only the
concurrency problem to deal with.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list