Test your skills through the online practice test: Python Quiz Online Practice Test

Related differences

Python vs JavaPython 2 vs Python 3

Ques 31. What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. 


Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time.

You'd have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Is it helpful? Add Comment View Comments
 

Ques 32. How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.


For example:

config.py: 
x = 0 # Default value of the 'x' configuration setting

mod.py: 
import config
config.x = 1

main.py:
import config
import mod
print config.x

 
Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

Is it helpful? Add Comment View Comments
 

Ques 33. How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:

def f(x, *tup, **kwargs):
  kwargs['width']='14.3c'
  g(x, *tup, **kwargs)

In the unlikely case that you care about Python versions older than 2.0, use 'apply':

def f(x, *tup, **kwargs): 
  kwargs['width']='14.3c'
  apply(g, (x,)+tup, kwargs)

Is it helpful? Add Comment View Comments
 

Ques 34. How do you make a higher order function in Python?

You have two choices: you can use nested scopes or you can use callable objects.

For example, 
suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b): 
  def result(x):
    return a*x + b
      return result

Or using a callable object: 

class linear: 
  def __init__(self, a, b):
    self.a, self.b = a,b
    def __call__(self, x):
      return self.a * x + self.b

In both cases: 
taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.

 
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear): 
  # __init__ inherited
  def __call__(self, x):
    return self.a * (x ** self.b)

Object can encapsulate state for several methods: 
class counter:
  value = 0
    def set(self, x): self.value = x
    def up(self): self.value=self.value+1
    def down(self): self.value=self.value-1
    count = counter()
    inc, dec, reset = count.up, count.down, count.set

Here inc(), dec() and reset() act like functions which share the same counting variable.

Is it helpful? Add Comment View Comments
 

Ques 35. How do I copy an object in Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method: newdict = olddict.copy()

Sequences can be copied by slicing: new_l = l[:]

Is it helpful? Add Comment View Comments
 

Most helpful rated by users: