[CentralOH] Code Review / Advice

eponymous at insight.rr.com eponymous at insight.rr.com
Thu Nov 19 11:36:48 EST 2015


Forgive me if this is not an appropriate use of this list.

I have written some code to enumerate the “public’ printable attributes of an Object and output them in JSON format. 

The code works, but seems both inefficient and like something for which there is already an undiscovered solution in the standard libraries. In particular, I dislike the conversion of  types and attributes to strings before testing a condition. 

I have included the code below, but you may prefer to view it on pastebin

http://pastebin.com/MiFAhwYK

All constructive feedback is welcome whether on topic or not.
 
----

import ipaddress
import json
 
ipnet = ipaddress.IPv4Network('192.168.0.0/24')
 
print(ipnet)
 
def ipAttr(obj,att):
        # Returns true for all non method attributes which are public
        return not str(att).startswith('_') and 'method' not in str(type(getattr(obj,str(att))))
 
def ipDict(obj):
        return {att: str(getattr(obj,att)) for att in dir(obj) if ipAttr(obj,att)}
 
print(json.dumps(ipDict(ipnet),sort_keys=True, indent=4, separators=(',', ': ')))
 
Thanks

Josh
---
 
192.168.0.0/24
{
    "broadcast_address": "192.168.0.255",
    "compressed": "192.168.0.0/24",
    "exploded": "192.168.0.0/24",
    "hostmask": "0.0.0.255",
    "is_global": "False",
    "is_link_local": "False",
    "is_loopback": "False",
    "is_multicast": "False",
    "is_private": "True",
    "is_reserved": "False",
    "is_unspecified": "False",
    "max_prefixlen": "32",
    "netmask": "255.255.255.0",
    "network_address": "192.168.0.0",
    "num_addresses": "256",
    "prefixlen": "24",
    "version": "4",
    "with_hostmask": "192.168.0.0/0.0.0.255",
    "with_netmask": "192.168.0.0/255.255.255.0",
    "with_prefixlen": "192.168.0.0/24"
}



More information about the CentralOH mailing list