Facebook's Python Business SDK uses a reserved keyword -- workaround?

783 Views Asked by At

In Python 3.7,

from facebookads.adobjects.adlabel import AdLabel 

results in

Traceback (most recent call last):
  File "/Users/mohan/growth-tools/facebook-experiment/main.py", line 4, in <module>
    from facebookads.adobjects.adlabel import AdLabel
  File "/Users/mohan/growth-tools/facebook-experiment/venv/lib/python3.7/site-packages/facebookads/adobjects/adlabel.py", line 22, in <module>
    from facebookads.adobjects.abstractcrudobject import AbstractCrudObject
  File "/Users/mohan/growth-tools/facebook-experiment/venv/lib/python3.7/site-packages/facebookads/adobjects/abstractcrudobject.py", line 564
    params=None, async=False, include_summary=True,
                     ^
SyntaxError: invalid syntax

The issue is, I think, that async has become a reserved keyword as of Python 3.7. Is there any workaround that would let me keep using this SDK?

5

There are 5 best solutions below

0
On

Try facebook_business instead of facebookads. See also this related answer.

0
On

If you think there is a genuine problem with the SDK, can't you just sudo cd there and then edit it?

If you can then the easiest option is to just go through every instance of async and check if it is the variable async, then replace it if it is.

0
On

Clearly, this module doesn't support 3.7. So you do as always where the vendor doesn't provide support: edit it and/or fork it.

E.g. replace async -> async_ across the module's codebase as in Error when building TclTk in Visual Studio 2017:

$ find /Users/mohan/growth-tools/facebook-experiment/venv/lib/python3.7/site-packages/facebookads \
! -type d -a -name '*.py' -print0 |\
xargs -0 python -c '
import sys,re
for fname in sys.argv[1:]:
 with open(fname,"rb") as f: l=f.read()
 (r,n)=re.subn(r"\b(async)\b",r"\1_",l)
 if n>0:
  with open(fname,"wb") as f: f.write(r)
'
0
On

Facebook has fixed this for the python library, use is_asyc instead as shown here.

0
On

I ended up just looping through all the files and replacing any instances of "async" with "async_", my solution below:

import os, re
path = r"path\to\facebookads"

python_files = []

for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
        if filename.endswith(".py"):
            python_files.append(os.path.join(dirpath, filename))

for python_file in python_files:

    with open(python_file, "r") as f:
        text = f.read()
        revised_text = re.sub("async", "async_", text)

    with open(python_file, "w") as f:
        f.write(revised_text)