You can do this:
d.pop("", None)
d.pop(None, None)
Pops dictionary with a default value that you ignore.
Answer from Keith on Stack OverflowYou can do this:
d.pop("", None)
d.pop(None, None)
Pops dictionary with a default value that you ignore.
You could use the dict.pop method and ignore the result:
for key in [None, '']:
d.pop(key, None)
Just check if self.members is not empty:
if self.members:
self.members.pop()
or, catch KeyError via try/except:
try:
self.members.pop()
except KeyError:
# do smth
You can use try/except to catch the KeyError raised by an_empty_set.pop(), or check the set first to make sure it's not empty:
if s:
value = s.pop()
else:
# whatever you want to do if the set is empty
dict.pop(key, default) will never raise a KeyError, if the key doesn't exist it just returns the default value. So your try:except: is not useful.
That aside using pop in such a way is fine, especially if you expect that case to be pretty common.
The issue with your second note is that the calling convention of your function is inconsistent, sometimes it returns two results and sometimes it returns none, so it's difficult to use.
- common Python idiom would recommend that your function raise an exception in case of an invalid email (whether missing or improper), that way the "happy path" always gets two values returned and the "unhappy path" is an exception handler, just replace your bare
returnby raising a suitable exception - if you don't want to raise an exception for some reason, then you need to either change the result to always be a single value (e.g. a dataclass), or you need to change your error cases to return something like
None, None(which is itself somewhat risky in a different manner than the current issue, asif some_function()will always pass).
If you decide to actually return something, then you should return values according to what is expected to be returned, like:
try:
email = account.pop('email') # no default value here, so exception can occur
except KeyError as ex:
return None, None
However, the better approach is to raise a specific exception:
try:
email = account.pop('email')
except KeyError as ex:
raise NoAccountFound() from ex
and let the caller handle it:
try:
some_function()
except NoAccountFound:
print("no account found...")
read the documentation for how pop works:
In [65]: dict.pop?
Docstring:
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
Type: method_descriptor
now check out your stack trace. it looks like django is trying to instantiate the object somehow without passing in the requisite keyword-args. so it's best to just add a default to pop
You can easily add default argument to both self_variables (self.content_types and self.max_upload_size) like so ...
def __init__(self, *args, **kwargs):
self.content_types = kwargs.pop("content_types", [])
self.max_upload_size = kwargs.pop("max_upload_size", [])