본문 바로가기
개발일기/PYTHON [codecademy]

**kwargs (Function Arguments)

by 르네팜 2022. 8. 14.

**kwargs = keyword + argument

저번 글에서 봤던 *arg와 비슷한데, *을 두 번 써서 dictionary(사전)의 형태로  무한대의 keyword와 value를 입력할 수 있다고 생각하면 된다. *arg와 마찬가지로 **만 붙이면 어떤 변수 이름을 사용해도 상관없다.

 

example:

def arbitrary_keyword_args(**kwargs):
  print(type(kwargs))
  print(kwargs)
  # See if there's an 'anything_goes' keyword arg and print it
  print(kwargs.get('anything_goes'))
 
arbitrary_keyword_args(this_arg='wowzers', anything_goes=101)

output:

<class 'dict'> 
{'this_arg': 'wowzers', 'anything_goes': 101} 
101

 

**kwargs 또한 *arg처럼 iteration이 가능하다. **kwargs는 dictionary형태로 값을 저장하기 때문에 .values() 방식을 사용하여 값을 iterate 해주면 된다.

 

example:

def print_data(**data):
  for arg in data.values():
    print(arg)
 
print_data(a='arg1', b=True, c=100)

# output:
arg1
True
100

 

 

또한 일반적인 위치 지정 인자들과 함께 사용할 수도 있다. 다만, python에서는 위치 지정 인자를 먼저 입력해야 한다는 점을 명심하자!

(만약 함수 괄호 안에 **kwargs를 먼저 쓴다면 SyntaxError가 발생하게 되니 주의하자.

#positional arguments first, then **kwargs
def print_data(positional_arg, **data):
  print(positional_arg)
  for arg in data.values():
    print(arg)
 
print_data('position 1', a='arg1', b=True, c=100)

# output:
position 1
arg1
True
100

 

 


연습문제 1.

preexisting code:

tables = {
  1: {
    'name': 'Chioma',
    'vip_status': False,
    'order': {
      'drinks': 'Orange Juice, Apple Juice',
      'food_items': 'Pancakes'
    }
  },
  2: {},
  3: {},
  4: {},
  5: {},
  6: {},
  7: {},
}
print(tables)

 

code:

# Checkpoint 2
def assign_food_items(**order_items):
  print(order_items)
  # Checkpoint 3
  food = order_items.get('food')
  drinks = order_items.get('drinks')
  # Checkpoint 4
  print(food)
  print(drinks)

# Checkpoint 5
# Example Call
assign_food_items(food='Pancakes, Poached Egg', drinks='Water')

 

output:

{'food': 'Pancakes, Poached Egg', 'drinks': 'Water'}
Pancakes, Poached Egg
Water

 


연습문제 2.

preexisting code:

tables = {
  1: {
    'name': 'Chioma',
    'vip_status': False,
    'order': {
      'drinks': 'Orange Juice, Apple Juice',
      'food_items': 'Pancakes'
    }
  },
  2: {},
  3: {},
  4: {},
  5: {},
  6: {},
  7: {},
}

def assign_table(table_number, name, vip_status=False): 
  tables[table_number]['name'] = name
  tables[table_number]['vip_status'] = vip_status
  tables[table_number]['order'] = {}

assign_table(2, 'Douglas', True)
print('--- tables with Douglas --- \n', tables)

def assign_food_items(**order_items):
  food = order_items.get('food')
  drinks = order_items.get('drinks')
  # tables[table_number]['order']['food_items'] = food
  # tables[table_number]['order']['drinks'] = drinks

print('\n --- tables after update --- \n')

 

code:

# Checkpoint 2
def assign_food_items(table_number, **order_items):
  food = order_items.get('food')
  drinks = order_items.get('drinks')
  tables[table_number]['order']['food_items'] = food
  tables[table_number]['order']['drinks'] = drinks

# Checkpoint 3
print('\n --- tables after update --- \n')
assign_food_items(2, food='Seabass, Gnocchi, Pizza', drinks='Margarita, Water')
print(tables)

 

output:

--- tables with Douglas --- 
 {1: {'name': 'Chioma', 'vip_status': False, 'order': {'drinks': 'Orange Juice, Apple Juice', 'food_items': 'Pancakes'}}, 2: {'name': 'Douglas', 'vip_status': True, 'order': {}}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}}

 --- tables after update --- 

{1: {'name': 'Chioma', 'vip_status': False, 'order': {'drinks': 'Orange Juice, Apple Juice', 'food_items': 'Pancakes'}}, 2: {'name': 'Douglas', 'vip_status': True, 'order': {'food_items': 'Seabass, Gnocchi, Pizza', 'drinks': 'Margarita, Water'}}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}}

 

댓글