patternpythonMinor
Python coding style from Java background
Viewed 0 times
backgroundjavastylepythonfromcoding
Problem
I am pretty new to Python and just wanted to make sure I am going in the right direction with my coding style.
After reading this, I'm not so sure.
The following is a convenience class that has operations used a lot in my main code.
```
import requests
try: import simplejson as json
except ImportError: import json
"""
Basic operations involving users
"""
#The URL of the API
api_root = "http://api.stuff.com/v1/core";
class UserOperations(object):
def __init__(self, headers):
self.headers = headers
def move_user(self,source_account,destination_account, user_id):
user_id = str(user_id)
#Get user
user = self.get_user(source_account, user_id)
if user is not None:
#Remove user from source account
self.remove_user(source_account, user_id)
#Add user to destination account
self.add_user(destination_account, user)
def get_user(self, account_id, user_id):
#Get user
user = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
#Throw exception if non-200 response
user.raise_for_status()
print "\nGet User " + user_id + ": " + user.text
#Check user exists
if user.json()['Data'] is None:
return None
#Return user
return user.json()['Data']
def remove_user(self,account_id, user_id):
#Delete a user
result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
#Throw exception if non-200 response
result.raise_for_status()
#Result of delete operation
print "\nDelete Result " + result.text
def add_user(self,account_id, user):
#Add user to new account
result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
#Throw exception if non-200 response
After reading this, I'm not so sure.
The following is a convenience class that has operations used a lot in my main code.
```
import requests
try: import simplejson as json
except ImportError: import json
"""
Basic operations involving users
"""
#The URL of the API
api_root = "http://api.stuff.com/v1/core";
class UserOperations(object):
def __init__(self, headers):
self.headers = headers
def move_user(self,source_account,destination_account, user_id):
user_id = str(user_id)
#Get user
user = self.get_user(source_account, user_id)
if user is not None:
#Remove user from source account
self.remove_user(source_account, user_id)
#Add user to destination account
self.add_user(destination_account, user)
def get_user(self, account_id, user_id):
#Get user
user = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
#Throw exception if non-200 response
user.raise_for_status()
print "\nGet User " + user_id + ": " + user.text
#Check user exists
if user.json()['Data'] is None:
return None
#Return user
return user.json()['Data']
def remove_user(self,account_id, user_id):
#Delete a user
result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
#Throw exception if non-200 response
result.raise_for_status()
#Result of delete operation
print "\nDelete Result " + result.text
def add_user(self,account_id, user):
#Add user to new account
result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
#Throw exception if non-200 response
Solution
-
Unlike in Java, not everything in Python needs to be a class. In Python we tend to reserve classes for representing things with individual state and common behaviour. If you just want to group some functions together, you can put them in a module.
-
You have no documentation. What do these functions do and how am I supposed to call them? In Python you should give every public class, function and method a docstring.
-
Why do you try importing
-
Your code is not portable to Python 3, but this would be easy to fix by putting parentheses around the arguments to
-
This code:
can be simplified to:
-
You have code like this:
in three places. You should make this a function.
-
It's not clear what the point of this line is:
All you ever do with
-
I prefer to use
would become:
Comment on updated question
You have failed to avoid the duplicated code: you have just moved it around.
Unlike in Java, not everything in Python needs to be a class. In Python we tend to reserve classes for representing things with individual state and common behaviour. If you just want to group some functions together, you can put them in a module.
-
You have no documentation. What do these functions do and how am I supposed to call them? In Python you should give every public class, function and method a docstring.
-
Why do you try importing
simplejson? This is just the externally maintained version of the built-in json module. You don't seem to use any simplejson-specific feature, so what's the point?-
Your code is not portable to Python 3, but this would be easy to fix by putting parentheses around the arguments to
print.-
This code:
#Check user exists
if user.json()['Data'] is None:
return None
#Return user
return user.json()['Data']can be simplified to:
return user.json()['Data']-
You have code like this:
VARIABLE = requests.METHOD(api_root + '/accounts/' + account_id + STUFF, headers=self.headers)
VARIABLE.raise_for_status()in three places. You should make this a function.
-
It's not clear what the point of this line is:
user_id = str(user_id)All you ever do with
user_id is add it to strings, where it will be converted to a string in any case.-
I prefer to use
str.format to build up strings, rather than +: the former tends to result in clearer code. For example:api_root + "/accounts/" + account_id + "/users/" + user_idwould become:
'{}/accounts/{}/users/{}'.format(api_root, account_id, user_id)Comment on updated question
You have failed to avoid the duplicated code: you have just moved it around.
Code Snippets
#Check user exists
if user.json()['Data'] is None:
return None
#Return user
return user.json()['Data']return user.json()['Data']VARIABLE = requests.METHOD(api_root + '/accounts/' + account_id + STUFF, headers=self.headers)
VARIABLE.raise_for_status()user_id = str(user_id)api_root + "/accounts/" + account_id + "/users/" + user_idContext
StackExchange Code Review Q#38890, answer score: 6
Revisions (0)
No revisions yet.