2

Now I use file-> download as->python(*.py) in jupyter notebook's UI to convert jupyter notebook to python script. However, it will convert all the \ to a long spaces (maybe a tab), e.g. In Jupyter notebook:

test_users_df = item_info_df.where(item_info_df.split=='test')\
                        .select(['user_id'])\
                        .distinct()\
                        .orderBy(['user_id'])

Converted python script will become:

test_users_df = item_info_df.where(item_info_df.split=='test')                            
.select(['user_id'])                            .distinct()                            
.orderBy(['user_id'])

Is there a way to keep the original format?

user21
  • 329
  • 2
  • 15

1 Answers1

2

I don't think there is a way around this (that I've found), but something I do to get around this is use parentheses () for line continuation instead of a backslash.

I think the debate is open on whether \ or () is best for line continuation, see the comments at https://stackoverflow.com/a/53180/7019148 for discussion.

I would change your code to:

test_users_df = (item_info_df.where(item_info_df.split=='test') 
                         .select(['user_id']) 
                         .distinct() 
                         .orderBy(['user_id']))

and the conversion from .ipynb to .py should work as expected!

tda
  • 2,045
  • 1
  • 17
  • 42
  • I dont think this works in general. What do you do when you have something like ``` a,b,c,d = \ long_named_function() ``` – cgnorthcutt May 29 '18 at 03:34
  • There is no way to do this at all in Python (see https://stackoverflow.com/a/40955425/7019148), but generally Jupyter notebooks aren't great for script development IMHO, so if your desired output is .py files, use an IDE. – tda May 30 '18 at 07:44
  • 1
    @cgnorthcutt Using ⏎ as a newline: ```a,b,c,d = (⏎ long_named_function())``` is valid and identical in meaning. I always break long lines in this style and never use backslashes. PEP 8 recommends this. See [this question](https://stackoverflow.com/questions/48830681/is-line-continuation-with-backslash-dangerous-in-python). It's annoying that Jupyter doesn't support backslashes since they're valid Python but they're almost never necessary. – goodside Dec 12 '18 at 05:55