st_bones
st_bones

Reputation: 129

how to pass additional argument along with *args in Python

I have a function that takes *arg and an additional positional argument. but when calling this function I am getting below error. Any help how to pass this additional argument

**error**:
export_bundle() missing 1 required keyword-only argument: 'dict'
from stix2 import MemoryStore, Identity
import datetime

timestamp = datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%S')

id1 = Identity(
    name="John Smith",
    identity_class="individual",
    description="Just some guy",
)
id2 = Identity(
    name="John Smith",
    identity_class="individual",
    description="A person",
)

dict= {"id":1234, "name":"abd"}

def export_bundle(self, *args, dict):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
    del mem

export_bundle(id1, id2, dict)

Upvotes: 1

Views: 1696

Answers (2)

VietHTran
VietHTran

Reputation: 2318

You declared the function export_bundle with variable number of arguments (*args), so if you want to define the dict argument at the end it needs to be keyword-only parameter (dict). You can call it as export_bundle(id1, id2, dict=dict) if you want to pass a value for dict.

def export_bundle(self, *args, dict):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
   del mem

export_bundle(id1, id2, dict=dict)

Upvotes: 3

Jeevan Chaitanya
Jeevan Chaitanya

Reputation: 1384

Always function parameters first & then *args, **kwargs

def export_bundle(self, dictm,*args):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
    del mem```

Upvotes: 0

Related Questions