Alternative locals () when printing a table with a header

[Python 3.1]

Edit: error in the source code.

I need to print a table. The first row should be a heading consisting of column names separated by tabs. The following lines should contain data (also separated by tabs).

To clarify, let's say I have the columns "speed", "strength", "weight". I originally wrote the following code using the related question I asked earlier:

column_names = ['speed', 'power', 'weight']

def f(row_number):
  # some calculations here to populate variables speed, power, weight
  # e.g., power = retrieve_avg_power(row_number) * 2.5
  # e.g., speed = math.sqrt(power) / 2
  # etc.
  locals_ = locals()
  return {x : locals_[x] for x in column_names}

def print_table(rows):
  print(*column_names, sep = '\t')
  for row_number in range(rows):
    row = f(row_number)
    print(*[row[x] for x in component_names], sep = '\t')

But then I found out that I should avoid using locals()it if possible .

. . , , f(), , . locals().

, print_table() f() ; .

?

+1
3
class Columns:
    pass

def f(row_number):
    c = Columns()
    c.power = retrieve_avg_power(row_number) * 2.5
    c.speed = math.sqrt(power) / 2
    return c.__dict__

, , .

+2

OrderedDict, . , , . column_names ( , , ), .

0

an alternative to locals () would use the inspect module

import inspect

def f(row_number):
    # some calculations here to populate variables speed, power, weight
    # e.g., power = retrieve_avg_power(row_number) * 2.5
    # e.g., speed = math.sqrt(power) / 2
    # etc.
    locals_ = inspect.currentframe().f_locals
    return {x : locals_[x] for x in column_names }
0
source

All Articles